Generics In C# – Its Usage And How It Differs From C++ Templates And Java Generics

Generics allow a type or method to operate on objects of various types while providing compile-time type safety. It can be used to achieve parametric polymorphism – a way to make a language more expressive, while still maintaining full static type-safety. Through Generics, you can generically define a member/method in a class that is valid for all the related types, or you can pass any data type to a function whose parameter has any template. Templates are commonly considered as a compile-time feature. Unlike polymorphism, through interfaces (and inheritance), there is virtually no overhead (more on that later) in using templates, because they are normally turned into equivalent source code during compilation.
In this detailed tutorial, I will tell you how you can implement them, the benefits of this programming model and its difference to Java and C#. Let’s start the journey!

How To Implement Generics?

In my previous tutorial on operator-overloading, I gave you the example of “Vector3f”. Let us continue from where we left. Suppose we want a class for holding three-point vector values (x, y and z), that is generic and accepts any data type including integer, float and double. In order to do that, we need to create different classes for different data types. Fortunately, through generics feature, we can define only a single class with generic semantics that implements the same methods for all the data types as long as the operation on them makes sense. Let’s call our generic vector class as “Vector3“. We can define such class as follows:

The formula to declare our generic class is as follows:

Having that in mind, we can use our class in the program as follows:

As you can see, we can easily create an object of “Vector3“ of any data type that we want. This greatly reduces the need to create separate classes for different types.The above example is for generic class. Note, however, is that you can not use operators on generic data type, because at a time of compilation, a compiler doesn’t know whether those operations make sense. That is a limitation of generics in C# (which I will explain later). However, you can nevertheless overload operators in a class if you are sure that a programmer will use only those types that make sense.

Generic Method

Consider a simple method for printing what a programmer passed to a method to console. Now, for printing different data types (int, float, string etc.) you need to define different methods of the same name (function overloading).

You can see that the implementation is same for all the methods, but as C# is strongly-typed language, you can’t pass double in the parameter for “int”, so we had to define different methods. Fortunately, through generics, you need to only define a single method.

Generic Interface

An interface can be generic too. Consider the following example:

How Generics Work?

As I previously mentioned, Generics is the compile-time feature – meaning it works during compilation of a program. It transforms the class, interface, function etc. that has generic type, into equivalent source code with different class, interface, function etc. of data types that is used when creating an object.

During initialization of an object, compiler will transforms above class into equivalent classes. This will be transformed into the following:

However, note that in C#,  the types are substituted during compilation, so there may be a slight overhead.

Difference to Java Generics

In Java, there is a concept of generics too, which, although looks similar in look, have quite different implementation. Generics in Java provide compile-time safety for type-correctness, but is partially considered as a run-time feature and it is somewhat similar to inheritance-polymorphism in practice. In Java, there is a process called type erasure, through which, type information is removed during compilation and there is no way to tell what was the type of a generic when it was instantiated during run-time. This is considered as a restriction and many programmers are dissatisfied with it. So, any algorithm that requires to know the original type cannot be implemented through generics in Java. You can’t do things like:

Because there is no way to tell during run-time what was the type of “T”. As I said earlier, Java has type erasure, it actually has run-time cost because behind the scene Java’s compiler actually casts the type, something like the following:

See this for more information.

Difference to C++ Templates

In C++, templates are a pure compile-time feature, due to which it greatly increases the compilation speed. The resulting program is bigger in size as well due to the boilerplate code templates in C++ create during compilation. Templates in C++ are more powerful than C# and Java, but are very complex too. It gives a terrible compilation speed during source code transformation. Both provide support for parameterized types. C++ provide substitutions of types during compile time. In C#, however, substitutions are performed at runtime.

In C#, you can not call arithmetic operators on generic type, though you can call user defined operators. In C++, the following code is valid:

C# neither support explicit specialization nor partial specialization which makes Generics not useful in some cases. See this for more information.


Generics is the most useful feature, especially in libraries. Its usefulness can not be dismissed when creating a library for other programmers, considering the fact that is implemented in collections in C#. I find it easy to achieve polymorphism through generics than through the interface

If you have any question, then please ask in the comments section below!

Understanding Abstraction in C#

In Object-Oriented Programming (OOP), abstraction is one of three fundamental principles (along with encapsulation and inheritance) that defines the paradigm. Through the use of abstraction, you can hide the unwanted details of the underlying data about an object in order to reduce complexity and increase efficiency (in some cases, which I will mention later). If you have some background in the art, you will realize that it works in the same way. For instance, if you are sketching an apple, it is not desirable to sketch the unwanted details around the apple; the details of an apple is the only thing that really matters to you. In this way, an object that is created through a class represents the original, without unwanted details. You can refer the resulting object itself as an abstraction, i.e., a named entity that is made up of selected attributes and behavior that is specific to a particular usage of the originating entity.

Abstraction is related to both encapsulation and data hiding. Through this design, you can separate interface from implementation. It is often considered the most useful technique in data hiding. It is not only useful in the program for which the design is originally implemented, but in other programs too; if you are creating some library that is going to be used by other programmers, then it is a very useful design for an API (Application Programming Interface) as it completely hides the implementation from a programmer. The users of your library won’t be distracted with the details of methods that does the magic; they would simply use them in the way how you like them to be used

In this tutorial, I will make you understand the concepts of Abstraction and how this design can be implemented in your C# programs. Even though the source code examples that I will provide may be valid for Java (or C++) too, I’m just focusing on C#. So, let’s get started!

Interfaces On The Rescue

Suppose you want to create some graphics library whose purpose is to simply draw a circle or a rectangle to a window. When designing the API with this design in mind, our concern is not how the methods should be implemented, but how a programmer is supposed to use it. Through interface, you can separate the common methods of different classes; this assures that any class that inherits from the given interface must implement the methods defined in the interface else the compiler will give you the errors. Let’s consider an interface “Drawable” with a method “Draw” that needs to implemented in the classes that inherits this interface.

Now, every class that inherit from “Drawable” must implement “Draw”.

In this case, a programmer do not need to worry about the implementation of “Draw”  in every class that implements the interface “Drawable”, they just use those methods in the way they are supposed to be used without worrying about the implementation of different “Draw” methods. Here, you also try to ensure that the entity is named in a manner (“Drawable” in this case should have an obvious “Draw” method) that makes sense and it has all the relevant aspects.

As abstraction provides a programmer a generalized view of the classes, a user of your library can easily examine the interface without reading the implementation, thus it enhances readability. Recall that I have mentioned that abstractness can increase the efficiency in some cases. To unpack what I said: Suppose you have several methods that have similar functionality of “Draw”, but you name them differently, let’s say “Draw” and “DrawOnce”, for drawing in a loop or drawing once respectively. Now the programmer can easily see how those methods are supposed to be used. Conversely, if you use a boolean member in a class, let’s call it “drawOnce”, to flag whether the method “Draw” should draw in a loop or draw once, there is a chance that a programmer will miss the detail and end up using “Draw” without flag of “drawOnce” set to “true” when he/she only wants to draw once, thus the resulting program will not be very efficient.

At this point, I should add that interfaces are linked with the concept of Polymorphism in a sense that it is considered the application of interfaces.

Understanding Polymorphism

Through Polymorphism, a programmer can use the derived class in the place of a base class. It is a way to generically use common methods. Polymorphism can be considered the applications of several concepts such as inheritance, generics etc. I won’t go into the details of Polymorphism and its every possible application. I will focus only on its application of abstraction.

In our example, any class can be passed to a method “Draw” of an instance of “Window” that implements the interface “Drawable”, resulting in expressive code and reduced complexity.

Now, a programmer who likes to draw different shapes other than rectangle and circle can create their own user-defined classes that inherit from “Drawable” and then simply implement the “Draw” method. In this way, the instance of a user-defined class can easily be passed into the method “Draw” of an instance of “Window”. Through the process, we obtained what we wanted in the first place, i.e., data hiding, thus we can conclude that abstraction is indeed a great design for libraries.


In this tutorial, I have showed you the concepts of Abstraction, how it is normally understood in the OOP, and how you can use its amazing power to harness your program. If you have any questions, then you can ask in the comments section below!

Functions / Methods in Java and C#

When we hear a term “Function” our mind create the image of an option or technology in a program that do something, so when we use the function, a program does a particular job. A function is simply a combination of several tasks written beautifully within a single label through a proper organization rules. In programming languages, a function is used to hold several lines of code that does something, such as, adding the two integers together, displaying a text on a console screen, etc. Through the use of function, you can cut the multiple lines of codes and paste into a function with a name (i.e., a name through which you will remember it) and then call (use) it whenever you need the functionality in your program without duplicating the same code throughout the program, thus FUNCTIONS REDUCES THE SIZE OF THE CODE.

In OOP languages (i.e., C# or Java), a function is implemented as a static method, which means that you need to declare a class first in order to use it, unlike in non-OOP programming languages (like C) where a function exists by itself. In C# and Java, a function is a part of an object and is defined in a class and every executed instruction is performed in the context of a method. So, for example, when we call “System.out.prinln()” (in Java) or “Console.WriteLine()” (in C#), we are actually calling a function which simply creates a line to the console, thus a function is named as “method” in OOP.

In this tutorial, I will teach you how you can implement functions in C# and Java to make your programming life more joyful!

Static Methods

As I said earlier, In OOP languages, we define functions as static methods. They are those methods which doesn’t change the state of a class (thus they are named ‘static’). It make sense that functions are implemented as static methods, because in functions we are interested in executing some arbitrary and we are not interested in changing the object’s state.

The syntax for defining a static method in a class is same for both C# and Java. It is as follows:

Considering this syntax, we can very easily define our function. Let’s define a function for adding two numbers, we can do so as follows:

You can see that it’s trivial to define a function, but then the task that our function does is trivial as well. Let’s define another function for calculating factorial:

We can use our functions in a program as follows:



Static Classes

Static classes are those classes whose only one instance is available to a program. These classes don’t need to be instantiated. It is useful feature in those cases where you know that an instance of a class that doesn’t need to be passed to other classes, but can be easily used without instantiating. A static class is a class which can only contain static members, and therefore cannot be instantiated. One of its examples is “GameSettings” for storing different settings in our game. We can define such class as follows:

The following is the syntax for using static method in a class:

Now we can use our static class in a program as follows:



Note that you can not use non-static members in static methods.


As you can see, Static Class can be used as a convenient container for a sets of methods that only run on input parameters and doesn’t modify the state of an object. In the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations like ‘cos’, ‘sin’ etc., without any requirement to store or retrieve data that is unique to a particular instance of the Math class, thus they don’t need instantiation to operate.

Functions are best suited for trivial tasks, especially when some task is duplicated several times in your program; hence you can simply create a static method in a class and call it whenever you need it. In which cases are you going to use functions?

Classes in Object Oriented Programming (C# and Java)

 In Object-Oriented Programming (OOP), there are two types of programming: class-based programming and prototype-based programming. Class is the most important concept in OOP, especially in class-based OOP (which is the dominant programming style in C#, Java, C++ etc.). It is a way to store properties and attributes of any object in a user-defined type, such as a car, dog, man etc. Think of it as a blueprint where you store all the information and then execute the operation according to the structure. In OOP, we manipulate different objects to perform something, which means that programming in OOP will force you to focus on data and not so much on logic and we are interested to know what the data holds. Basically, you would start with creating the structures first and the logic second.

We need an object or instance of class to manipulate itself and the other objects, which is created through a given class. You might have already heard of data encapsulation when talking about OOP. Class provides the support for data encapsulation by supporting various ways to hide data from a user, thus the user will be able to use only those features that you intended. The created instance (or object) not only holds a logic (code, procedures, etc.), but also a state, and thus can be manipulated by other objects.

In this tutorial, I will teach you the basics of Class in OOP using Java and C# as examples. Let’s get started!

Understanding the syntax

The syntax for declaring a class is same in both Java and C#.

As I mentioned earlier that a class is used to hold data, so it wouldn’t to create a class without a data!A class can hold members (i.e., variables) and methods (i.e., functions in a class that process the data). Following is the syntax to define variables/methods in a class:


  • access modifier = keywords that limits the access of a member/method, i.e., public, private and protected
  • return type = data type that is returned from a function
  • member name = any variable name

So for example, if we want to create a class for our object “Player”, we can do so as follows:

Here you can see that I defined properties and functions of player in our class “Player”. You can define as many members or methods you want, there is virtually no limit, though older computers will take much memory. Similarly, we can define other classes too:

Understanding public, private and protected

They are the access modifiers for telling a compiler whether it should allow any member/method of a class to be accessible within its class or in other classes too. ‘public’ makes a member/method available to other classes, while ‘private’ makes it available only within the class where it is declared. ‘protected’ makes it available within the class and derived class – which is a bit hard to explain, as it involves the concept of inheritance that I will teach you in later tutorials.

(Note: In C#, there is an another access modifier called “Internal” which limits the access of member/method to current assembly)

Creating an instance of a class

Recall that I said, you need to create an instance of a class in order to use it in your awesome program. The simple formula to create an instance of a class is as follows:

Using the formula, we can easily create an instance of a class in our program:

In our class, we could also declare “state” as protected because there is no inheritance involved in our program, so the results would be the same; that is, you wouldn’t be able to access “state” in your “Main” function.


You can now see how easy it is to use the feature of classes in your OOP programs. A class is arguably the best way to store data to easily manipulate various states in a program.

If you have any additional questions, then you can ask in the comments section below!

How to generate random number without repetition in C++

Click here to get straight to the point.

If you are programming in C++ for a while, then you probably got in a situation where you want to get some random number between two given ranges; you might have used old C-function rand() with an initial seed of NULL time, such as the following:

Here, rand() plays a role of random number generator (RNG). A random number generator is simply an object that produces a sequence of pseudo-random values. Note that we must reset the “seed” with an initial value of time when the program is started, else it won’t give random values.

This is quite a common way to get a random number in C. However, the problem that you may have faced with it is that you get the same number several times in your program; that is, it doesn’t distribute numbers properly. That isn’t something you want to do.

In C++, <random> header provides many functions and templates which provide better distribution. With the advent of C++11, it got even more useful functions and random number generators. Following is its usage:

You will now get better distribution. However, it can still give you same number, so this approach can be suitable for programs where it doesn’t matter such as lotteries, etc.

How to generate random number without repetition in C++

Suppose, you are creating a vocabulary builder program, and you want to ask random questions from a player. Now, the program isn’t supposed to ask the same question again from the player when he/she answers a question, but rather it should ask different question every time a player answers one question.

In my previous article, I have told you different ways of finding an element in a container. We will use the approach where two containers (we will use std::vector) will be used: one for storing numbers and other for storing the previous numbers given by our random generator. Following is its implementation:

Here, we are asking for different number from our RNG until the number isn’t present in our container of previous numbers. Now, it will give different number that isn’t given before by random generator in our given range.

Note that std::mt19937 is a RNG called Mersenne Twister 19937. There are some other RNGs as well such as std::minstd_rand, std::mt19937_64, etc. You can use this approach whenever you need to get a random number that is different from the previous numbers.


In this tutorial, I have showed you how to generate random number without repetition in C++. You shouldn’t have any problems now.

Did this article help you in making your programming life easier?

How to find an item in a container in C++

When I was creating a vocabulary builder in C++, I had to find an item in a container of std::vector which stored some values. I looked for its solution on the internet, but couldn’t find what I wanted.

Finding an element in a container or array is quite a common task in programming, yet some programmers don’t know the number of ways it can be done. <algorithm> header provides several useful functions for manipulating containers and one of those functions is std::find, which is especially defined for STL containers like std::vector, std::list, etc.. This can be used on legacy C arrays as well. std::find is used for getting the iterator of a given range.

Through std::find, you can easily find whether an element in a container exists or not. It takes three parameters: First iterator, Last iterator and the element that you want to find in a container. Following is its usage:

If your vector is ordered (if not, then do so with std::sort), then you can use std::binary_search which yields O(log n) worst-case performance, which is way more efficient than the first approach. For sorting elements in a std::vector, you should use std::sort and NOT std::qsort, because the latter is quite expensive for std::vector. Note that if you want to find an element in a container at several times in your program, then you are better off using std::list, because it doesn’t need to be sorted and thus searching is more efficient. Following is its usage:

As you can see, how easy it is to find an element through std::find function.

Another easy way to find an element in a container is by using std::find_if alongside with the lambda feature of C++11. It finds an element in a container with a given condition; if you want to get the first odd / even number in your container that holds numbers, you can define the function for it and then pass it in its parameter. It takes three parameters: First iterator, Last iterator and the function that defines the condition. Following is an example of its usage:

Now you can decide, which way is better suited for your case.

Using std::find on legacy C arrays

If you are using C++, then it is highly recommended to use static / dynamic arrays from STL containers (i.e., std::array, std::vector, etc.) for storing number of elements, but for any reason, if you are using C arrays (i.e., int array[10]), then you can use std::find as well. Following is the way to do that:


In this tutorial, we have learned the different ways to find an item in a container, whether it’s the STL containers or legacy C arrays.

Is there any other way that you know, through which an item in a container can be found in C++? Please let me know in the comments section below!

Operator Overloading In C# With Examples

What is Operator Overloading?

Operator-Overloading in C# that acts as a syntactic sugar in the code and ease the use of libraries in your programs. Most of the built-in operators in C# can be redefined or overloaded; that is, you can give them the meaning of yours!

This feature is not present in C#’s competitor language Java, which makes C# appealing to the many programmers who are building large libraries / frameworks.

Through it, you can create your own user-defined operator implementation of available operators for your own user-defined classes and structs.

This feature is particularly useful if you are creating some library as it will make your library easier to use for others.

In this tutorial, I will teach you its usefulness, misuses and how you can implement them in C#.

Which operators can be overloaded in C#?

In C#, unary operators (“+” as in “i++” etc.), binary operators (“+” as in “obj1 + obj2“ etc.) and comparision operators (“>”, “<” etc.) can be overloaded, while conditional logical operators (&& and ||), array indexing operator, cast operator ([]) and assignment operators (+=, -=, etc.) can not be overloaded. See the full list of overloadable operators on MSDN.

What is the usefulness of Operator Overloading in C#?

Operator overloading is useful in such cases where you want to use basic operations on objects as if those objects are primitives like numbers, strings, etc.

Suppose you have a class for storing three floats (x,y and z) corresponding to mathematical vectors. Let’s call our class “Vector3f”. This class is used for the storing and operating three-dimensional vectors. Mathematical vectors are commonly used in graphics libraries (especially 3D libraries / engines). We need different methods to operate on them: method to add our vector values, subtract them, multiply and divide them, etc. You can create such a class with these methods as follows:

Now, we can use this class in our program and operate on the objects as follows:

Wouldn’t it be cool to simply perform operations on them like “vec1 + vec2“ just like you do “2 + 3“ because it’s pretty obvious from the look that adding them means adding their components (x, y and z)?

Operator overloading on the rescue

Operator-overloading reduces the need to explicitly call methods for such trivial tasks. If you were using Java, you would just stick with the use of methods for operating on vectors due to lack of support of operator-overloading in the core language. In C#, we can use operator-overloading to implement syntactic sugar for trivial tasks like “vec1 + vec2“ through it as follows:

Now, we can simply use them in our program as follows:

Any operator (that can be overloaded) can be overloaded in a class in the following way:

So, if you want to implement equality “==” and inequality “!=”, you can do so as follows:

Similarly, if you want to overload increment “++” and decrement “–” operators, then you can do so as follows:

Now, these overloaded-operators can be used on the objects in the program as follows:

Its common misuses

As it eases the use of libraries, some people just for the sake of small code base in the use of the library, use operator-overloading in places where there is a chance of an ambiguity in its meanings. You should only overload operators on logical types where its meaning is obvious. Consider a class for holding an array:

In this case, we overloaded “+” operator so that we can add any integer to all the members of an array. But, the problem with its usage is that a programmer doesn’t know which number in an array is being added and since there is no addition through indexing, it is pretty ambiguous whether the variable being added is simply an integer or an array of integers.

A simple way to make your code less ambiguous is to provide the equivalent methods for overloaded-operators. So, for instance, if a user of your library can’t understand operators that you have overloaded, then he/she can anyway use methods for achieving the same results.

Note that you should overload in a symmetric manner; that is, if you are overloading “+” and “-”, then it also makes sense to overload “*” and “/”, similarly if you are overloading equality “==” then you should overload inequality “!=” too.

Summing Up

In this tutorial, we have learned the following:

  • Meanings of Operator overloading.
  • Its usefulness when your job is to ease the library usage.
  • Operators which can not be overloaded.
  • Cases where operator-overloading isn’t appropriate.


Operator-overloading is a really useful feature if it is used properly where its meaning make sense. Its usage is perfect in user-defined logical numbers, vector-like structures (quaternions, matrices, etc.) etc.

In short, it should be used in places where the operations on objects are obvious from the look.

Will you be willing to use this feature in your library? Or would you just prefer to use methods for the sake of consistency with your Java code? Tell us your thoughts in the comments section below!

Dynamic Memory Allocation in C – Its usefulness with examples

Dynamic Memory Allocation in C refers to manual memory management of variables through the use of several functions from the standard library (<stdlib.h>) such as malloc, realloc, calloc, free, etc.

If you are wondering what I meant by “Dynamic”, then just know for now that C has different types of memory management: Static, Automatic and Dynamic.

For instance, the moment you declare a variable, the program creates some memory required for storing the value of a variable of some data type, which it automatically releases when the variable is at the end of its scope. Consider the following example:

Here, the program releases the memory allocated for storing the element of a data type “int” when the program ends. This is an example of Automatic Memory Allocation (we will learn more about it later).

In this article, you will learn how you can use dynamic memory allocation in C programming language. Let’s first study the different types of memory management in C.

Static Memory Management

In this type of memory management, your variables are allocated in main memory at compile-time either on the stack or in other sections of your program.  You do not have to reserve extra memory for using them, but on the other hand, you lose control over the lifetime of this memory, i.e., a variable in a function is only there until the function finishes. Consider the following example:

Here the memory of our declared array “array” will be released upon the function termination; that is, once the function is finished doing its job!

Automatic Memory Management

In this type of memory management, variables are allocated on the stack upon entry into a block and exists for the duration of that block; that is, it come and go as functions are called and return.

Both of the above memory management requires that the size of the allocation must be compile-time constant.

Dynamic Memory Management

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don’t free the allocated memory when it’s no longer necessary, you’ll run into memory leaks, which may cause your application to crash, and because of it you cannot allocate more memory at some point. Memory leaks can be very dangerous because the system may run out of memory. Consider the following example:

Here, the malloc function is used to perform an allocation of contiguous memory. To free this allocated memory, C provides free function.

Allocation functions

Standard library of C provides several functions for allocating the memory: malloc, calloc and realloc.  

malloc function allocates a block of size bytes of memory, but it doesn’t initialize the values; that is, you will get indeterminate values if you print the pointer values into your console screen.

calloc function allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.

realloc function reallocates a block of memory. Through it, you can change the size of the memory block that is already pointed to your pointer. It returns a void pointer, so you need to cast it to your data type. The first parameter is the pointer to previously allocated memory block.

In all of the above cases, we used free function to free the allocated memory.

The usefulness of Dynamic Memory Allocation in C

Dynamic Memory Allocation is needed in those circumstances when you need full control over the time the memory is released. Let’s learn its usefulness.

1) Dynamic Array Creation

The most basic usage of Dynamic Memory Allocation in C is the creation of “Dynamic” arrays; that is, the arrays that can change its length. Consider the following program:

2) Full Control of Memory

Through these allocation functions, you know for sure when the program is releasing the memory. It is very useful in things like concurrency control, and if you know what you are doing, then it can increase efficiency as well.

Summing Up

In this tutorial, we have learnt the following:

  • There are three types of memory management in C: Static, Automatic and Dynamic.
  • Dynamic Memory Allocation is necessary for creating Dynamic Arrays in C.
  • Manual Memory Management is required for the maximum efficiency in various algorithms.

C is a low-level programming language, mostly used for systems programming. This is manifested with the usage of dynamic memory allocation (manual memory management).

For simple tasks, such as, storing static values in an array, then you don’t need to use dynamic memory allocation, as it will only make the code harder to read and unsafe too.

In C++, manual memory management is done mostly through new and delete operators, so if you are using C++, then it is highly recommended to use C++ operators rather than resorting to use C functions.

Did this tutorial teach you something new you didn’t know before? Please let us know in the comments section below!

Properties in C#

Properties is a simple and yet useful feature of C# programming language. It basically enables a programmer to use object member syntax (i.e., object.methodname) for setters and getters functions. Through it, you can read, write, or compute the value of a private field very flexibly.

If you have used C++ or Java in the past, then you most likely have seen methods in a class for reading and writing member variables, such as “setLentgh(int length)” and “getLength()” for setting the length and getting the length respectively. In C#, properties are actually special methods called accessors.

In this tutorial, I will teach you how you can use properties feature in C# and I will show you the cases where it is very useful.

How do I use Properties in C#?

The following is the simple syntax for defining properties in a class:

Using the properties in a class is as easy as follows:

Now, we can easily use our class in a program, we can do so as follows:

As you can see, how easy it is to use this feature in C#. Now, the question that might arise in your mind: What good this feature does to us? (Except the fact that “_length” is renamed to “length” in use)

When should I use Properties in C#?

The place where properties come handy are those places where you need to implement member syntax for getting/setting a data from an array or struct, because without properties, you can only resort to implement setter and getter methods for that. For instance, suppose the following class “Vector3f” for holding three members: x, y, z:

But, you like to store the values of a vector in an array instead (probably because a programmer wants to do specialized operations internally, which can be done only on arrays such as SIMD operations for efficiency, etc.) along with the methods to set/get the x, y and z value from an array.Without properties feature, the class would look like the following:

With properties feature, you can simply implement the setters and getters for x, y and z values as properties. We can do so as follows:

Now you can use the class in a program, we can do so as follows:

Another very useful case of properties is when you want to implement something in setter / getter, yet you want to use properties as if you are accessing a variable instead. MSDN provided a great example of a class “TimePeriod” which stores a time period in seconds, but a property named “Hours” specify a time in hours and performs the conversion between hours and seconds.

Additionally, Properties can also be used to make some variables ‘read-only’. For instance, arrays in C# have a property “Length” (which gives the length of an array) that can only be read.

Summing Up

In this tutorial, we have learned the following:

  • Properties is a very useful feature of C#.
  • Using this feature in your C# code is a matter of writing setter / getter functions.


Properties in C# is one of the “killer” features of the language, because it makes the libraries / assemblies development and usage so easy. This feature encourages programmers to use C# for developing libraries for .NET framework instead of other programming languages, because no other similar static typed language has this feature.

What is your opinion on this feature? Let me know in the comments section below!

How to sleep the CPU through cross-platform sleep function in C/C++

If you need your CPU to sleep for a while; that is, wait for some time without any activity, then you need to call system functions in your program. For instance, if you want to show some text for 2 seconds, then you can sleep the CPU to simulate the effect.

Unfortunately, there is no cross-platform way to sleep the CPU; Windows provide sleep() function in <windows.h> header, which takes milliseconds in an argument, while Linux provides sleep() in <stdlib.h> function which takes seconds and usleep() which takes milliseconds in an argument.

To overcome this cross-platform problem, we will use macros to detect whether the code is compiling under Windows or Linux. Following is its implementation:

Now, you can call SLEEP with an argument of milliseconds for sleeping the CPU whether you are on Windows or Linux. Apart from that, you can also use rlutil::msleep() from rlutil library to get cross-platform sleep function.