C# - class and struct difference

Important differences between struct and class in C#
 - struct is value type but class is reference type (value and reference type description here)
 - struct does not support inheritance
 - struct does parameterless constructor generated by compiler and we can NOT overload such constructor (this constructor is used for assign default values to struct fields) while class can has many overloaded constructors

Just to compare In C++:
 - the only difference is that default modifier for struct is private while it is public for class

Read more »

Blog's new layout

As you noticed this blog has new layout from today. I hope you like it. I think new layout looks better and more modern than previous one. Please, write you opinion about new layout in comments. If you have some ideas how to make this blog better, all ideas are welcomed.



Enjoy new layout and articles.
Read more »

C# - Value type and reference type

C# is language which operates with two kind of types:
  • value type - type where only one space of memory is allocated. It is related for primitive C# types like: int, char, float, bool etc. as well as for struct types. If you copy value type to another type new instance of object will be created.
  • reference type - type related to class objects. When we are declaring such class object, two memory spaces are being allocated. Object of class type and reference for such object. If you copy reference type to another reference type, only reference is being coping. It means that both references will be able to operate (ex. modify) the same object. Threfore when we modify object using one reference and will try to get its fields values using second reference, fields will have values after modification. As opposed to C++, there is possible to create reference type being not related to any object - null reference. Reference types in C# are very similar to pointers in C++.
Let's see example before for better understanding: Output of this example is: In point I we are declaring class TestClass which will be base for our reference type object.

In point II we are declaring struct TestStruct which is base for our value type object.

Point III presents initialization and assigning basic values for three different objects:
  • class type object being reference type object
  • struct type object being value type object
  • primitive type (int type) object being value type object
and displaying value of our objects in point IV. Point V is key point of this example. Here we are passing our objects to the function and trying to modify its values there in order to check difference between reference type and value type.

Point VI prints values of our objects after invoking changeValuesOfClassAndStruct() function.

As you can see value of class type is being changed, while values of struct types and int type are not being changed. It is because default parameters passing to the function in C# is passing by value. This means we are copying object which we are passing to the function and copy of such object is being visible only within function.

However when we are passing reference type object we are passing reference to our object by value (copying reference to object - creating second reference to object), which allows as to see modified objects after exiting function using first reference to the object. So second copy of our reference is visible only withing function, but thanks to first copy of reference to the same object which is visible outside the function we can see modified object outside of function.

Reference and value types are one of major basic concepts which every C# developer should understand. This concept sometimes confuses people switching to C# from C++ programming language, where reference to object always have is marked using '&' character. In C# it is not required - instead we need to remember that every class type is reference type.

Code of above example can be downloaded from this blog's GitHub repository. You can find it here: Value and reference types

Read more »

C# - Calling one constructor from another

In order to call one constructor from another constructor in C# programming language you can use below syntax:

class Plane
{
 Plane (){}
 Plane (int a) : this() {}
 Plane (int a, int b) : this(int a) {}
}

In above example constructor Plane (int a) invokes parameterless constructor Plane(). Constructor Plane(int a, int b) invoke two above constructors nested.

Read more »

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 »

C# - Assembly unit

C# defines new translation unit of application composition called assembly unit. Microsoft MSDN website defines assembly unit in following way:

Assemblies form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions for a .NET-based application. Assemblies take the form of an executable (.exe) file or dynamic link library (.dll) file, and are the building blocks of the .NET Framework. They provide the common language runtime with the information it needs to be aware of type implementations. You can think of an assembly as a collection of types and resources that form a logical unit of functionality and are built to work together.

In short, assembly unit is translation unit having some integral functionality compiled to one .dll or .exe file. In C# solutions assembly unit usually is one C# project or C# library.

Read more »

C# - PascalCasting vs camelCasting

PascalCasting vs camelCasting - types of naming function or variables names.
  •  PascalCasting - naming when we starts with capital letter and each next word start with capital letter. Used for properties, methods, types
  •  camelCasting - naming when we starts with lower case letter and each next word start with capital letter. Used for parameters, fields, variables.
Read more »
Powered by Blogger.

Sample Text

Sample Text

Sample text

Sample Text

Social Icons

Social Icons

Followers

Featured Posts