Friday, April 17, 2015

Structure with constructor in C#

Before some time , I have written basic introduction post about Structure in C#. In this blog post we are going to see how we can have constructor with Structure. As we all know structure is a value type so it stored on stack. So let’s create a structure like follow with constructor.
public struct Customer
{
    #region Fields

    public int CustomerId;
    public string FirstName;
    public string LastName;

    #endregion 

    #region Constructor

    public Customer(int customerId, string firstName, string lastName)
    {
        CustomerId = customerId;
        FirstName = firstName;
        LastName = lastName;
    }

    #endregion
}
Here you can see I have created Stucture with parameter. As we all know structure is a value type so when initialize the it at that time we need to give values to its elements so that’s why default constructor without parameter is not supported in C#.

You can find whole discussion about that at stackoverflow at following link.

http://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net

Now let’s create a object of structure in our console application like below.
class Program
{
    static void Main(string[] args)
    {
        Customer customer = new Customer(1, "Jalpesh", "Vagdama");

        Console.WriteLine(customer.CustomerId);
        Console.WriteLine(customer.FirstName);
        Console.WriteLine(customer.LastName);
    }
}
Now once you run this application. It will print fields of customer structure as expected.

structure-with-constructor-console-application-output

That’s it. Hope you like it. Stay tune for more!!.

You can find complete examples of all structure related blog post at github on -https://github.com/dotnetjalps/StructureCSharp
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews