Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# object initialization options

Doesn't object initialization outside of a constructor break encapsulation ?

Given:

class MyClass 
{  
    public string _aString;  
}

Shouldn't the _aString member be private and instantiated via a call to the constructor (constructor omitted here):

 MyClass test = new MyClass("test");

Instead of the alternate method of object initialization:

MyClass test = new MyClass { _aString = "Test" };
like image 528
Scott Davies Avatar asked Jul 08 '09 23:07

Scott Davies


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


2 Answers

"Doesn't object initialization outside of a constructor break encapsulation ?"

Well, no. As you rightly pointed out you can only initialize properties that are already accessible in your current scope. (public, internal etc)

This kind of Intialization is really just some syntactic sugar around construction of a class and assigning values to properties, It is very useful for Anonymous classes and Linq select clauses.

like image 148
Tim Jarvis Avatar answered Oct 19 '22 07:10

Tim Jarvis


It is usually considered bad practice to expose public fields... it may be acceptable in some cases, for instance if the field is marked as readonly (which means it must be set in the constructor). Instead, you should make this field private and expose it through a property, which may or may not be readonly, depending on its purpose :

class MyClass
{
    private string _aString;
    public string AString
    {
        get { return _aString; }
        // uncomment to make the property writable
        //set { _aString = value; }
    }
}
like image 32
Thomas Levesque Avatar answered Oct 19 '22 06:10

Thomas Levesque