Archive | C# RSS for this section

Beginners: Access Modifiers Exemplified

In the recent past, I have been involved in code review where I found a code base which is dominated with “public” access modifiers, and I was like, seriously?. In my recommendations I had to point there was lot to be done in terms of code accessibility levels, not everything belonged to the public :).

And therefore in this post, we will be expounding modifiers found in the .net framework. Modifiers are used to modify the declaration of types(Interface, Class, Struct) and type members (fields, properties,events, delegates, methods).

In C# there are quite a number of modifiers but in this post we are going to major with access modifiers. Access modifiers specifies the accessibility of types and type members. They include

  1. Private
  2. Internal
  3. Protected
  4. Protected internal
  5. Public

Remember only one access modifier that is allowed in a type except when using “protected internal”. Depending on the context in which a member declaration occurs, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default access modifier is used

To bring the point closer home, I would like to think of a family set up where we have a father, mother and children, and the father has a few properties including cars.

We will be using the following classes “Calculator.cs” in assembly “CalculatorLib”


public class Calculator
 {
   private void Add()
    {
    }

     internal void Subtract()
     {
     }

     protected void Divide()
     {
     }

     protected internal void Multiply()
     {
     }

     public void Modulus()
     {
     }
 }

The following image shows what of “Calculator.cs” is visible when called from “CalculatorClient.cs” class in the same assembly

Figure 1

Figure 1

The following image shows what of “Calculator.cs” is visible when called from “Program.cs” class in a different assembly

Figure 2

Figure 2

The following image shows what of “Calculator.cs” is visible when called inside one of its own members

Figure 3

Figure 3

The following image shows what of “Calculator.cs” is visible when called from “CalculatorDerived.cs” class which is its derived class

Figure 4

Figure 4

Private

This proves to be the least permissive and restrictive acess modifer.A private member is only visible to the containing type and its members. Its used in class members and nested class. Remember its not used in top level class.

The private method “Add” can only be accessed by any other member within the class and not outside the class. It’s not even visible to other classes within the same assembly.

Refer to “Figure 3”, you be able to identify “Add” method visible in the containing class and not visible to any of the other figures

Internal

This level of accessibility can used in top level classes, nested class and there members. They are acccessed by the members of the same assembly. The use of internal is in scenarios where you intend components in the same assembly to communicate and share functionalities but as without exposing the functionality to the world (other assemblies).

And so even if you give out you component in terms of a .dll, the internal members are not exposed to the consumer of your library/assembly.

Figure 1, 3, and 4, you are able to see “Subtract” since they are in the same assembly. It’s not visible in Figure 2 since that another assembly

Protected.

This is a member modifier, and can also be used with nested classes. Protected members are only visible to derived classes and the declaring type as well. This modifier is used hand in hand in inheritance as we will come to see later. One other note is that struct cannot be protected as they cannot be inherited.

Visible in Figure 3 since its in the declaring class and also in Figure 4 since its “CalculatorClient.cs” has derived from “Calculator”.

Protected internal

Just as the name is suggesting by the combination of the modifiers, it means that every member with this modifier can be assessed by both types in the same assembly as well as derived classes.

“Multiply” is visible in Figure 1 because of the “internal” modifier and visible in Figure 4 because of the “protected” modifier.

Public

This  is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members. Anything with public modifier is visible literally every where.

“Modulus” which is public, is visible anywhere you should be able to see it in every figure above.

Hope this post,helps you to use the access modifiers knowledgeably and confidently.

The source code is hosted on github

Happy coding!!

How To: Convert ASP.NET Web API to Azure API app

In my last post, I introduced and discussed about the new azure API apps.  It’s really nothing more than your asp.net web API with a new way and form to expose the metadata so to speak.  Its actually a web app with other additional features for hosting. Azure API  is hosted within a web app.

In the pipeline to Azure API app, there a gateway which performs other stuff before reaching the Azure API app. The gateway is just another web app able to perform extra functionality like authetication with providers.

Every resource group with that contains an API app also includes a gateway. The azure API app expose there metadate via a new representation swagger. Its a new powerful representation of RESTful API.

In this post we are looking at how to convert an already existing ASP.NET web api to azure api app. I will be using visual studio 2013.

Open visual studio 2013, and create a new ASP.NET Web api.

aspnetwebapi

To keep things simple, I am not using any authentication in this post. We will make a few changes to ValuesController, make sure it look like show below


public class StudentController : ApiController
{
public IHttpActionResult Get()
{
var students = Students();

return Ok(students);
}

private List<Student> Students()
{
var students = new List<Student>();
IGenerationSessionFactory factory = AutoPocoContainer.Configure(
x =>
{
x.Conventions(c => { c.UseDefaultConventions();});
x.AddFromAssemblyContainingType<Student>();
});

//Create a session
IGenerationSession session = factory.CreateSession();
students = session.List<Student>(50)
.First(25)
.Impose(x => x.FirstName, "Bob")
.Next(25)
.Impose(x => x.FirstName, "Alice")
.All()
.Impose(x => x.LastName, "Pius")
.Random(10).Impose(x => x.LastName, "Peter")
.                                                  All().Get().ToList();

return students;
}
}

In our code we are using “autopoco” package to generate object to test with. So far this is just the normal ASP.NET web api. You can run the application and hit “http://localhost:26467/api/Student&#8221; and you will see the response of 50 students.

So how do we convert it to azure API app? Good question, and the essence of this post. To do that you simply add a new package called “swashbuckle” as shown below. Go package manager and search for “swashbuckle”

swashbuckle

When this is installed a new file should be added in your App_Start, “SwaggerConfig.cs”. Ensure your solution looks like below

Swaggerfileconfig

That’s the file that makes your expectations come true. Nothing much, nothing less. So run you application and hit the following url, “http://localhost:26467/swagger&#8221; which takes to a screen like below:

Swagger_documentation

If your screen looks like above then everything so far looks good. So this generates a documentation of all the api operations in the project, you need to know it uses the same pipeline as how ASP.NET WEB api generate help pages.  Click “Try it out!” and you will see a json response from the “GET” operation.

But where is the metadata? Navigate to “http://localhost:26467/swagger/docs/v1&#8221;, and this will generate a metadata file which is json in nature. We will talk on how to use this metadata file to generate a client sdk and other uses.

metadata

So from the image above.

1. Paths holds a collection of the API controllers in the projects

2. Indicate a API controller in our project “/api/Student”

3. Within every API controller, all available operations tagged with the http verb are listed.

4. The responses the operation supports.

That’s it!! 🙂 We have managed to convert/enable an ASP.NET Web api to a azure api app.

Source code can be on github

Quick look at azure app services

For a good period of time, azure has been offering azure websites and mobile services among others like biztalk services. Recently as part of the Azure SDK 2.5.1 release they have used a new term “App services”. As I tried to understand what this means, I was abit confused but found that its not a completely new term, its a combination what we know, with added features and advancements

App services basically is a collection of the things we already know and new additions that will help you with new integrations, building of rich, engaging and intelligent applications to help you scale as your business grows.

In the application services azure websites are termed “Web apps” while mobile services are termed “mobile apps”. If you visit your azure account you should be able to see these changes. Basically the current websites can easily be converted to web apps and therefore you are not going to rewrite your websites.

App services therefore contains

  1. Web apps
  2. Mobile apps
  3. Logical apps
  4. API apps.
  5. BizTalk API Apps

API apps

This new feature add on top of the ASP.NET Web API extending it with swagger metadata and an easy way to manage on the azure portal. It helps you easily build and consume API in the cloud The API Apps are behind a gateway which manages various add-on functionalities like authentication and update policies.

The gateways are created when you create a new API  App and they live in stardand resource groups. Just like we generate the WSDL information with svcutil, you can easily the swagger metadata on your Azure API Apps on visual studion by adding “/swagger/docs/v1” to your browser address.

Another functionality is that you can package your Azure API App and upload it to azure market place for other consumers to use it.

As we will see in future posts, you can easily generate your Azure API App sdk in a few click. Existing ASP.NET Web API can be converted to Azure Web API without any complexity by simply adding Azure App API SDK.

With  API Apps, you can easily on the azure portal define the access levels for you API App. There are three access levels namely

  • Public (Anonymous) -Meaning does not require any form of authentication to access
  • Internal -Only apps in your subscription can access and not available for public access
  • Public (Authenticated) -Publicly available but you require authentication for access.

With API Apps, from azure portal you choose, by a click how you intend to update in case the API App is updated. You can choose from Off (You dont need update), Inherit  and On meaning it will auto-update.

Something to note is that when you get an API app from the market place, you get an independent instance of that API App in your subscription, and there it runs in “isolation” from others, hence the reason to update when major or minor updates are done to the source package in the market place. 🙂

Web Apps

As mentioned earlier this were the formerly known as Websites. Some of the known feature includes

  • They run .Net, node.js, Java,php and even python
  • Web jobs for long running tasks, scheduled tasks
  • Integrated VS publish and remote debugging
  • Continous Intengrations with github, bitbucket, and Visual Studio Online
  • Auto-load balance and auto scale
  • Virtual networking and hybrid connections
  • Site slots for staged deployments

In azure portal all of your existing websites instances are now web apps in app service. Web hosting plan is now app service plan, and an app service plan can host any app type of app service e.g Web, Mobile, Logic or API Apps.

Mobile Apps

Formerly mobile services, and mobile services continue to be available as a stand alone service and remain fully supported as of this writing. Mobile app intengrates all of the functionality of Mobile Services and they include the following features.

  • Web jobs for long running tasks
  • CI with github, bitbucket, VSO
  • Auto-load balance auto scale GEO DR
  • Virtual networking and hybrid connections
  • Site slots for staged deployments
  • Supports single sign-On from various identity providers like facebook, google, microsoft account, twitter Azure AD
  • Offline sync which helps improve app responsiveness by caching server data locally on the device, make the app more resilient against network issues and syncing data across multiple devices helping solve any conflicts on the same record from different devices.
  • Push notifications via scalable push notitication engine, you can send personalized push notification however you want it addressed.
  • Easy connection to SaaS APIs.

Logic Apps.

This brings automation as a service by bringing new application for easy automation both with cloud and on premises systems. Some of its features includes:

  • Visually create business processes and workflows
  • There are a number of  pre-built templates to get started
  • Out of box support for popular SaaS and on premise applications
  • You can create you custom logic apps
  • There are biztalk APIs for expert integration scenario

That was just for introduction there is more information to come on the same.

As always happy coding 🙂

When to use Response.Redirect and Server.Transfer?

Recently I had to respond to an issue which was a result of using wrongly of the aforementioned in web forms. Each of them are used with a specific purpose and not as an alternative to another. And so let see when to use either of them and in what situations.

They do have distinct notable differences. One of them being with Response.Redirect the browser url changes to the targeted page while in Server.Transfer the url remains the same.

With Response.Redirect a HTTP 302 message is usually sent do the browser  while in Server.Transfer all happens without the browser knowing anything, and it ends up recieving a different content from the requested.

Another difference is that the Server.Transfer consumes more server power in comparison to Response.Redirect.

Server.Transfer cant send a user to an external site while Response.Redirect can.

When to use Response.Redirect:

  • we want to redirect the request to some plain HTML pages on our server or to some other web server
  • we don’t care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)

When to use Server.Transfer:

  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don’t need to show the real URL where we redirected the request in the users Web Browser

I do hope this will help someone out there who needs to find which to use and when. This might not be exhaustive but it’s worthy you consideration

Happy coding!

What really is Katana and owin?

What really is really Katana? How about Owin? After playing around with Katana, I really found it worthywhile to post about what I have found regarding them. OWIN ( initials for Open Web Interface for .NET )is a set of specifications that defines a stardand interface between which .NET web servers and web applications communicates. Katana on the hand is an implementation of the OWIN.

A little history of ASP NET is that it was released in early 2002 or sometime around then, with .NET framework 1.0 and it was meant to bring a web experience for customers who included classic asp  and desktop line of business application developers like VB 6.

There were alot of stuff and concerns brought forward by these two customers, which meant that the framework was to be monolithic leading to inclusion of all concerns in one single package, System.Web.  The package included just to mention a few features, Modules, handlers, sesssion, cache, web forms and controls. And all this was meant to run on IIS.

With time the System.Web package became complex because with every new requirement it was added to the package. By default most of the features were turned on by default to seamless intengration .

By then, IIS was the only hosting for ASP NET and most of the features for ASP NET runtime map one to one with those found on the IIS. This was a problem and in around 2008 ASP NET MVC was released which atleast enabled rapid developement and was distributed via nuget. Come 2012 ASP NET WEB APi was released , and unlike ASP NET MVC, WEB API does not rely on System.Web in anyway. Initially WEB API was started by the WCF team, which later was sent to ASP NET  team who added capabilities like self hosting.

Thats a little background and history of a few players which brought the idea behind katana. In a modern web application, you  can expect to have at least some static files, web api, rendering engine perhaps MVC razor, and perhaps SignalR for some real time communication. And the question is perhaps, couldn’t it be awesome to be able to compose all these or other multiple frameworks together to create a single server?

And there comes Katana which is a set of components for building and running web applications on a common abstraction which is, OWIN…

The primary interface in OWIN is a application delegate or simply AppFunc, which is a delegate that takes IDictionary<string,object> and returns a Task, and the signature is like Func<IDictionary<string,object>,Task>

Katana is meant to offer the following

Portability by reducing to the least primitives as possible

Composability ->Its really easy to compose modules together that will participate in all aspect of the incoming requests.

Performance and scalability -> Uses Async throughout and there is total decoupling of web application and host.

A typical Owin enabled application should have the following layers.

1. Application ->This is your application which could be like ASP NET MVC

2. Application framework -> These could be regular OWIN component implementation giving simple to use API to developers to easily plug-in to the pipeline. For example, we have signalR and Web API, though currently SignalR uses OwinHost.

3.Server –> This is responsible to binding to a port and channels request to the pipeline for processing. e.g SystemWeb, HttpListener o or the new Weblistener

4.Host –> This is a process managers that spans new process call to your code and provides and puts the pipeline in place eg this could be IIS if you will be hosting on IIS, could be OwinHost.exe which is the katana implementation or even you custom process.

Currently, katana embraces conventions over configuration. So when you install owin, when you code runs it goes through you code via reflection looking for a class with name of Startup and a method named “Configuration” taking IAppBuilder interface as the only parameter. IAppBuilder is an interface used to compose modules together. There are alot of extension methods built on top of IAppBuilder which we will explore at a later post.

To recap, let write a simple application and host on a console application. I am using visual studio 2013. Open VS 13, File -> New Project ->Console Application, give a nice name and click Ok. This is  a simple console application with nothing to do with Owin. So open Package Manager Console and install the following nuget packages

Install-Package Microsoft.Owin.

install-package microsoft.Owin.Host.HttpListener.

install-package microsoft.owin.hosting

And at least it should be close to

Package-isntallation

With in we will now add the basic code to host our application. And just as we said we will need to add a class with a name “Startup” and a method “Configuration”. Quickly let to that. After we finish setting up the nuget packages then copy and paste following code to your program.cs file as is

using System;
using Microsoft.Owin.Hosting;
using Owin;

namespace KatanaTest
{
 class Program
 {
 static void Main(string[] args)
 {
 //Create a url
 string uri = "http://localhost:8080";

using (WebApp.Start(uri))
 {
 Console.WriteLine("Server is starting");
 Console.ReadKey();
 Console.WriteLine("Stopping the server");
 }
 }
 }

///
/// Note the name "Startup"
 ///
 public class Startup
 {
 ///
/// Note the name and parameter
 ///
 ///
 public void Configuration(IAppBuilder app)
 {
 //Simple write to the response stream here
 app.Run(x =>
 x.Response.WriteAsync("We are just testing this application"));
 }
 }
}

Run the code and open you favourite browser and paste http://localhost:8080/. The result which would be “We are just testing this application” printed on the browser. This means that you have successfully written you first owin application hosted on a console application.
Katana is utilized in the ASP NET MVC 5 project template for authetication. In our case we have utilized the simplest method ever to write something on the response stream. But there is alot of extensibility and capabilities with katana where you can plug your own middleware or component in the pipeline, which is how the authetication is plugged in the ASP NET MVC 5. Another post regarding this soon.

But just to point out is that all you really need to write a katana module, is to write a class which has a constructor takes one arguement of type  Func<IDictionary<string,object>,Task>, and this represent the next module in the pipeline which you manually call from your component.

Just to demonstrate lets a middleware component that prints some message to the response

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using Owin;

namespace KatanaTest
{
 class Program
 {
 static void Main(string[] args)
 {
 //Create a url
 string uri = "http://localhost:8080";

using (WebApp.Start(uri))
 {
 Console.WriteLine("Server is starting");
 Console.ReadKey();
 Console.WriteLine("Stopping the server");
 }
 }
 }

///
/// Note the name "Startup"
 ///
 public class Startup
 {
 ///
/// Note the name and parameter
 ///
 ///
 public void Configuration(IAppBuilder app)
 {
 app.Use();
 //Simple write to the response stream here
 app.Run(x =>
 x.Response.WriteAsync("We are just testing this application"));

//Plug our component here

 }
 }

public class HelloWorld
 {
 private Func<IDictionary<string, object>, Task> _next;
 public HelloWorld( Func<IDictionary<string,object>,Task> next)
 {
 _next = next;
 }

public Task Invoke(IDictionary<string, object> environment)
 {
 var response = environment["owin.ResponseBody"] as Stream;

using (var writer = new StreamWriter(response))
 {
 return writer.WriteAsync("Hello!!");
 }
 }
 }
}

Its as easy as that, and now when you run the application you see “Hello!” on the browser. Something worthy noting here is “owin.ResponseBody”, which’s one of the key in the Environment dictionary. For now take that dictionary as the HttpContext which contains all the information about a request. There are more Owin specific keys in the dictionary which we will explore in a later post.

That’s it for now, there is more to come on this same topic especially on how to write to write and hook up your own modules in the pipeline. You may also be interested in Checking-out-the-Helios-IIS-Owin-Web-Server-Host which I may recommend to get some information on the topic.

Happy coding and kindly get involved via comments, questions or suggestions. Thanks for reading 🙂

Abstract classes or interfaces?

Many of the times, I have seen the question of what factors should one consider either to implement a functionality in terms of abstraction, and this narrows down to if one should employ abstract class or interfaces.  A few days ago I was surprised when reviewing some code and just to brainstorm the developer,  I asked him a simple question, why did you choose to use abstract class rather than an interface?  Guess the response.. I just thought its good to use abstract class rather than interfaces. I didn’t have any other question for him but found it useful to demisfy this here for him, and others who would have the same kind of response to such a question.

I do agree that the choice of using any of them can be a daunting task.I will try to summarize what I have and wha I have found useful on the internet on this post. But  lets start at looking at the definitions of each:

An abstract class is a class that cannot be instantiated but must be inherited. The class can contain some default implementation for the child classes to use, and this methods should be non abstract methods. If an abstract method need exist, then it should be modified with abstract keyword and does not contain a body.

An interface on the hand is a type definition similar to class except that it purely represent a contract between an object and its user. And so its just a collection of members definitions e.g method, properties, events etc without any implementation.

So this brings to the question of who support or does what? Here are do’s and don’ts for each of them.

  1. Instantiation: Abstract classes cannot be instantiated away from their derived classes, meaning that there constructor are called only by their derived classes. Interfaces on the hand cannot be instantiated.
  2. Abstract classes can provide abstract members which base class MUST implement while all interfaces members MUST be implemented in the base class. So you can not implement partial interface, if you don’t need an implementation or you will not use some interface members you may need to leave stubs. e.g ConvertBack method for IValueConverter is usually not implemented but most implementation of the interface leave a stub, and this bring to the Interface Segragation Principle
  3. Extensibility: Abstract classes are more extensible than interface. You can alter an abstract classes without breaking any version compatibility. And note this extensibility is for non-abstract members. Interfaces on the other hand, if you have to extend you will have to create a new interface, otherwise you break the existing clients. Consider a situation where you are employed and after sometime you get a pay rise, you actually and should sign a new contract which looks the same as the previous with with the new  salary figures appear.
  4. Virtual members: Abstract classes allows for virtual members with default implementation for the deriving classes while for interfaces all members are automatically virtual and cannot contain any implementation.
  5. Accessibility modifiers: You can control accessibility of some members in abstract classes while all members of an interface are public by default.
  6. Inheritance: Being a rule in C# specification multiple class inheritance is not supported meaning that a class cannot inherit from more than one classes. On the contrary multiple inheritance is supported with interfaces

With that in place there are some guideline you should follow when deciding which one to use and when to use it.

  1. If you anticipate to create multiple versions of a component you may use abstract classes reason being it’s easy to create and version your components. For example by changing or updating the base class all inheriting classes are automatically updated whilst in interfaces they do not support versioning. Once an interface is created it cannot be changed you will have to create a new one. The analogy being once you sign a contract with your employer, and happens you get a pay rise you sign a new contract, you don’t manipulate the previous.
  1. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
  2. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
  3. If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

So too much of theory lets dive and see how we can establish some, if not all of the aforementioned points. So we are going to use an aspect of polygons. Basically we have a number of polygons which have different ways of calculating their areas. So we will employ both, interface and abstract class concepts.

 public interface IRegularPolygon
 {
 int NumberOfSides { get; set; }
 int SideLength { get; set; }

double GetArea();
 }
 public class Octagon : IRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public Octagon(int length)
 {
 NumberOfSides = 8;
 SideLength = length;
 }

public double GetArea()
 {
 return SideLength * SideLength * (2 + 2 * Math.Sqrt(2));
 }
 }

We also have an abstract class approach of the same.

 public abstract class AbstractRegularPolygon
 {
 public int NumberOfSides { get; set; }
 public int SideLength { get; set; }

public AbstractRegularPolygon(int sides, int length)
 {
 NumberOfSides = sides;
 SideLength = length;
 }

public abstract double GetArea();
 }
 public class Triangle : AbstractRegularPolygon
 {
 public Triangle(int length) :
 base(3, length) { }

public override double GetArea()
 {
 return SideLength * SideLength * Math.Sqrt(3) / 4;
 }
 }

Assuming that  you have implemented you get a requirement that you need to add a way to calculate the perimeter of the polygons. And knowing that, to calculate the perimeter of a polygon is just multiplying the number of sides with the length of one side.  With the abstract class implementation it really straight forward all you need to do is as below:

 public double GetPerimeter()
 {
 return NumberOfSides * SideLength;
 }

With the interface implementation you cannot just add the function declaration since this will break the existing clients. An easier way is to have a new interface with all the previous declaration or rather employ interface inheritance where you create a new interface with the new perimeter function inheriting from the IRegularPolygon. I would go with the latter.

Just to keep the post short, we end by looking what is in the framework which employs abstract classes and intefaces. In the BCL we have System.IO.Stream class, which is an abstract class. It contains some implementation of various methods as well as abstract and virtual methods which deriving classes implements. Some of the deriving classes include:

  • MemoryStream
  • FileStream
  • BufferedStream

With the interface, we have List<T> class which implements a list of interfaces which also show interface inheritance and best application of Interface Segregation Principle. Some of the interface it implements are

IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

So we end the post to make sure its not too long,  having demonstrated a couple of points I leave it to you to try the rest and poke me if any issue arises or if you need some clarity or some of technical engagement.

Its my hope you will consider the above mentioned points next time you find yourself in a dillema of which one to use, abstract or interfaces.

Again happy coding  and bye for now 🙂

C# Virtual Keyword trap

What does virtual keyword stand for?

Virtual exists in different programming languages though with different names and rules of how it should be used. E.g in C# its “virtual”.  With little experience of Java, I understand that all non-static methods are by default virtual functions, and therefore only methods modified with final keyword cannot be overridden as well as private methods which are not inherited.

So from the short and simple introduction, you can easily deduce that, by marking a method or a member virtual, you are giving authority to all child classes to  override and inject there own implementation. Override meaning that they can use their own implementation of the method/member instead of the base class implementation of the same method/member.

One thing to remember is that there is a hierarchy in derivation and execution of virtual members, since they can be overriden by many child classes. And so the rule  is that, only the most derived type will be executed depending on the object you are in.

So lets see what this might be bringing in our scenario.


class Shape
 {
 public Shape()
 {
 Draw();
 }
 public virtual void Draw()
 {
 Console.WriteLine(this.GetType().Name);
 }
 }

To note here is that the virtual method is called in the constructor, and remember the rules of the most derived takes precedence.

Another class that inherits from Shape as follows


class Circle : Shape
 {
private  int [] _coordinates;
 public Circle()
 {
_coordinates = new int[] { 1,2};
 }

public override void Draw()
 {
Console.WriteLine("{0} {1}", _coordinates[0], _coordinates[1]);
 }
 }

So in this class, we declared a array _coordinates and initialize it in the constructor. The is then used in the overridden method, just to see what happens. So in my calling class I set it up like so:


class Program
 {
 static void Main(string[] args)
 {

//Null exception
 Circle circle = new Circle();

//Null exception
 Shape shape = new Circle();
 Console.ReadLine();
 }
 }

When I run the above code so far, I get this screen

error2

I am creating a new instance of Circle class. The cause the constructor of Shape class to be called. In the Shape constructor we are calling Draw method. Our expectation here would be to see “Shape” printed on the console.

Which is not the case. The Draw method called in the base constructor, invokes the Draw method in the child (Circle) class since its the most derived, find an uninitialized int array, whence the null exception as we try to access first and second items in the array.

The consequences of this is that you can end using an object in unstable state. So you should be very careful when using virtual members in a constructor.

The Shape Draw method will only be called when you are creating a instance of Shape

Happy reading!

%d bloggers like this: