TagProperties

PropertyInfo

Type’s class GetProperties method returns us with a array of PropertyInfo objects. Similarly GetProperty method provided with a name of Property returns us a  PropertyInfo object. It allows us to access a lot of information and interaction concerning specific property, such as:

Does property have get or set accessor,

Properties Attributes,

Name,

Return type,

Allows us to change it’s value.

And so on…

Next time we will continue with MethodInfo class.

 

Constructor

Constructors are a public methods with the same name as a class were they resides. Constructors are always created with a class, weather we write it ourselves or if class creates it for us(although it will not be visible ). Role of constructors is to initialize fields when we instantiate class. It is possible to create multiple constructors. Adding „: this()“ after parameters of constructor with parameters will execute default constructor before constructors with parameters. To easily create constructors type ctor keyword an new one will be generated for you.

 

If you have ever initialized class you have consumed constructors in one way or another. Example of consuming constructors would be in previous example where we have instantiated ClassWithConstructor class with string “Mike” and integer 1.

 

Is it possible to forbid class to initialize constructor?

Yes it is, just create empty one and set private access modifier.

 

What about other access modifiers? Can I use them all?

Public, private, protected, internal, or protected internal access modifiers are allowed to be used with constructors.

 

How can i initialize base class constructors ?

Simply type

after constructors parameters . Remember, you don’t have to supply parameters for base class constructor  because base constructor will always be called before derived class constructor, weather we call it or not.

Properties

It is good practice to keep our fields private but so far we had to create at least two methods to access or change their values.

 

Why not star using properties? You consume properties as fields and write them (almost) as methods.

Simple property example:

 

But why stop there we can add more functionality to our properties, like set our string name to Upercase, return default value or check if integer is a positive number.

 

A property that has both accessors is read-write property. Properties with only get accessor are called read-only properties, properties with only get accessor are called write-only properties.

 

When you only need basic property without any additional logic, you could create auto-implemented property without filed (actually compiler creates one for you).

Simple isn’t it 🙂

© 2021 LearnC#WithDarko

Theme by Anders NorenUp ↑