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" };
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 ...
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? 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.
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.
"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.
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; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With