C# - Enumerations and bit fields

Enumeration is basic C# type mostly used for increase readability of code and make variable type safety.

Assume that we would like to use weekdays in some variable. We can create create int variable for it and assume that following numers (1-7) are associated with following weekdays. This would be enough but every user which will read our code should know about our assumptions to have no problems with analyze. Additionally someone can accidentially assign value being out of range 1-7 which can cause unexpected problems.

Better solution for above problem is using enumeration. Let's see following example:

Output of this example is:

In point I we are declaring our weekdays enumeration. Declaring is vary easy - we are using enum NameOfEnumeration syntax putting enumeration values into curly brackets, separated by comas.

Point III shows how to use enumeration. We are using enumeration type as any other type in C#. We are creating variable of our enumeration type. After that we can assign only values from our enumeration into that variable. That mechanism protects us by problem of assigning out-of-range unexpected value to variable. When we are trying assign other value than enumeration value we will receive compilation error.

You can also notice that our code has better readability right now. Comparison of
  day == Days.Sunday
is definitely better understandable than
  day == 7

In point II we are seeing one more use of enumeration types. We can create bit fields using enumerations which has better readability than just naming bits with following numbers. In order to declare it we are using [Flags] directive before enumeration declaration. As you can see we are defining following powers of 2 values to following bits representing LEDs.

In point IV we are setting bits our bit field using bit operators | (or) and we are checking whether bit is set using & (and) bitwise operator.

Above example you can find and compile github repository: https://github.com/xmementoit/CSharpAdventureExamples/tree/master/csharpBasics/enumsAndBitFields

Read more »

C# - Protection of field modification

C# provide two field modifiers for protection of field modification. Except of const keyword well-known from C++ we have additional readonly keyword in C#.
So we have three levels of field modification protection in C#:
  • private bool fieldName - such field cannot be modify outside class but can be modify inside
  • private readonly bool fieldName - such field can be modified in constructor of class only (useful for variables which should be once initialized and not modified later. In terms of properties - readonly properties can never be modified.
  • private const bool fieldName - such field can never be modified

See how those modifiers are working on the example below:


In points I, II, III we are defining fields with different modification protection levels. In points IV we have constructor of our TestClass and in point VIa we have one additional function for modification values of our fields.

First lets's analyze constructor modifications.
  • point V - we have modificableField which has not any modification protection. So it can be modify anywhere within class - also in constructor. No compilation error.
  • point VI - readonly protected field - it can be modify within constructor only - we are within constructor - no compilation error
  • point VII - const protected field - it cannot be modify anywhere - if you uncomment that line you will receive compilation error because you are trying modify field which is immutable
Now let's see on trying of modification our fields inside non-constructor public method:
  • point VIII - the same situation as in point V - we can modify this field - no compilation error
  • point IX - readonly protected field and we are outside of constructor, so we cannot modify this field - compilation error when you uncomment this line
  • point X - const field - the same situation as in point VII - compilation error when you uncomment this line
Code of this example you can download and check from here: https://github.com/xmementoit/CSharpAdventureExamples/tree/master/csharpBasics/fieldPropertyDifference

Read more »

C# - Field and Property difference

Instead of classic class field definition, C# adds one more class element - property. Sometimes there is hard to understand difference between field and property in C# for beginners.

 Main difference is:
 Field is just simple variable within class, while property is field wrapped in two functions: getter and setter.

So in general, if you define property, compiler silently creates invisible field for that property make that field accessible by get and set functions which are wrapped in property name. Thanks to that we can use properties like public fields in our code with encapsulation keeping.

Let's see below example:

Output of that example is:

In point I we are defining normal field - private field, because 'private' is default protection level in C#.
In point II we are defining default property. As we can see we have two keywords (get and set) within definition of that property. Those keywords defines default getter and setter for out property. Thanks to that we can use that property as public field (encapsulation is being kept thanks to get and set functions within property definition) - see points V and VII.

What is more we can customize property get and set functions according to our needs. Take a look at point III. We are defining there TestFieldProperty which has customized get and set function. That property is related to our private testField, so we can use it to modify testField according to our needs. In this example when we are using assignment operator for our TestFieldProperty assigning its value 10 as in point VI, we are actually assigning value 20 to our testField. Thus, when we are getting value of TestFieldProperty in point VIII, it will return value 20 (because it is actual value of testField according to our customization of get function in TestFieldProperty).

Code of above example you can find on github repository related to this blog here:
https://github.com/xmementoit/CSharpAdventureExamples/tree/master/csharpBasics/fieldPropertyDifference

Read more »

C# - Protection Levels

Because C# is object oriented programming language its class implementation allows using encapsulation mechanism.

 Encapsulation is mechanism which allow hide some functionality within class or object to avoid its access from outside of that class or object. 

 Encapsulation is very useful in order to make protection for some operation and make them invoke in only one known place of code. Thanks to that we have easier control on such encapsulated properties or functions.
 In order to define encapsulation we have protection levels which allow us make or prevent access to fields, properties and methods of our class.

 C# has 4 levels of protection:
  • private - fields can be used within objects of this class only. Default protection level in C#
  • protected - fields can be used within objects of this class and in classes derived from this class
  • public - fields can be used from any place in the code
  • internal - this is new protection level and it is default protection level for classes. It means that class can be used by other classes within own assembly only. More about assemblies you can find here: Assembly unit
For better understand protection levels, see the example below:

We defined 4 fields of different protection level (in points I, II, III, IV). Because our privateInt field is private we need to define two public accessible functions to set and get its value (getter (point V) and setter (point VI) - it is very common method of access to private fields keeping encapsulation).

Now take a look on point VII. We have not direct access to private values so direct assignment (as in commented line below point VII) is unavailable. In order to set value to private field we need to use our publicly accessible setter function.

The same situation is for getting value of private field (point VIII). We need to use public getPrivateInt() function in order to do that.

Of course if we were have access to protectedInt variable in above example we would also need to define publicly accessible getter and setter. It is because protected fields are accessible within class where are defined and within classes derived from class where protected fields are defined.

Now take a look at point XI. We do not have compiler error here, because we are accessing our internalInt field from the same assembly where testObject class is defined.

One more important information about protection levels you can find in point X. What is protection level of defaultProtectedInt? Its protection level is 'private'. It is because 'private' is default protection level for fields in C# (the same as in C++).

Above example you can download and compile from here:
https://github.com/xmementoit/CSharpAdventureExamples/tree/master/csharpBasics/protectionLevels

Read more »
Powered by Blogger.

Sample Text

Sample Text

Sample text

Sample Text

Social Icons

Social Icons

Followers

Featured Posts