0

Does initializing custom type do initialization for all props inside it ? I am asking this regarding performance and consumption of memory at client. In dot net if I create custom type something like

   public class myCustomType 
   {
     public string prop1 {get;set;}
     public string prop2 {get;set;}
     public string prop3 {get;set;}
     public string prop4 {get;set;}
    }

when somewhere else in code I do

var parOfmyCustomType = new myCustomType (){ prop1 = "stingToHold" };
var listOfCustom = new list<myCustomType>(){ parOfmyCustomType };

Regrading of memory consumed, does my app using memory for all sting props when I create myCustomType and set prop vale of only one

adopilot
  • 4,340
  • 12
  • 65
  • 92

2 Answers2

2

When you create properties with an empty get; set; definition the class the property is basically equal to the following:

public class myCustomType {
  private string _prop1;
  private string _prop2;
  private string _prop3;
  private string _prop4;

  public string prop1 {
    get { return _prop1; }
    set { _prop1 = value; }
  }
  public string prop1 {
    get { return _prop1; }
    set { _prop1 = value; }
  }
  public string prop3 {
    get { return _prop; }
    set { _prop1 = value; }
  }
  public string prop4 {
    get { return _prop4; }
    set { _prop4 = value; }
  }
}

The backing string fields (_prop1 - _prop4)are initialized to null (as are all reference types in C#). So bascially the data portion of that class would contain 4 "pointers" to strings that initially all point to null (depending on architecture that would be 4 * 32 bits or 4 * 64 bits or 16/32 bytes for every instance of the custom type.

Each string you create will use it's own memory (well, not always - you might want to search for "string interning"). But no memory gets allocated inside the custom type to store string data if that is what you're concerned about.

Oliver Ulm
  • 531
  • 3
  • 8
1

Each instance of myCustomType will contain four string references plus the usual per instance overhead. If an instance points to four strings these take up memory as well.

Community
  • 1
  • 1
Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317