0

I was testing a class in Linqpad and constructed a basic class but cannot get my head around how the two classes differ in execution. Can someone please help me out?

public class name // 1
{
    public string name1 {get;set;}
    public surname surname = new surname();
}

public class name // 2
{
    public string name1 {get;set;}
    public surname surname {get;set;}
    public name()
    {
    surname = new surname();
    }
}
public class surname
{
    public string surname1 {get;set;}
    public string surname2 {get;set;}
}
Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79

3 Answers3

3

The former compiles to the same as:

public class name
{
    public string name1 {get;set;}
    public surname surname;
    public name()
    {
        surname = new surname();
    }
}

So the only difference is that in 1 you have a field, and in 2 you have a property. Since it is public, you should use a property. See Why use simple properties instead of fields in C#? for reasons why.

As an aside, a C# naming convention is that all properties, classes, and methods are PascalCase, not camelCase, so all of the things in your examples (with possible exception of the surname field) should begin with a capital letter.

Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

i rewrite your classes, clr define your code like this

public class name // 1
{
    private string _name1;
    public string get_name1()
    {
         return _name1;
    } 
    public void set_name1(string value)
    {
         this._name1=value;
    } 
    public surname surname = new surname();
}

public class name // 2
{        
    private string _name1;
    public string get_name1()
    {
         return _name1;
    } 
    public void set_name1(string value)
    {
         this._name1=value;
    } 
    private surname _surname = new surname();
    public surname get_surname()
    {
         return _surname;
    } 
    public void set_surname(surname value)
    {
         this._surname=value;
    } 
}
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
0

One is a field. The other is a property. The surname property in name2 is translated by the compiler into getter and setter method pairs.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794