TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

C#- New Instance creation in a constructor Vs new in a member declaration, VB.NET

Is there any difference in creating new instance in constructor or create new instance as member declaration. initialize variable within constructor or outside constructor,which is best? Is there any performance or memory difference? These are some basic doubts many developers have.

Is there any difference in creating new instance in constructor or create new instance as member declaration. initialize variable within constructor or outside constructor,which is best? Is there any performance or memory difference? These are some basic doubts many developers have.

In actual, They are more or less same.Difference is only a programming style.

Consider the class example below.

public class SampleClass 
{ private Class1 c1 = new Calss1(); //Instance creation during member declaration private List<string> lstClass; // Instance creation in constructor public SampleClass() { lstClass = new List<string>(); } }


Here there are two class instances c1 and lstClass.c1 instance instantiated by member declaration and lstClass by using constructor.

Constructor allows you to create instance if needed,but member declaration instance will always be created.If you don't want any instance creation depending on the parameter passed through a constructor(or any other dependency) there is no any advantage of using constructor,instead you can save few code lines by intializing through declaration itself and avod writing default constructor only for this.

But If you have to address any sort of dependency during instance creation then constructor based approach is mandatory.See sample below.Here the Initialization is done by the parameter passed thrugh the overloaded constructor.

class SampleClass
{
    pprivate Class1 c1 = new Calss1();
    private List<string> lstClass;
   
    public SampleClass(List<string> stringList)
    {
        lstClass = stringList;
    }
}

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading