Definite Assignment Rule in C#


Introduction
In the programming languages like C and C++, we define any variable and accidentally used it as information before giving any value. C and C++ languages have no such in-built feature which can recognize it but C# does not allow us to use an unassigned variable this rule is known as Definite Assignment Rule. We must assign a value to a variable before use it; otherwise we will get a 'compile-time' error.
Consider in C++ Language
Let's take a look at example given below in C++ Language, it has a main method having an unassigned variable named 'sampleValue' but when we run this, no error comes out. Even this display some value say it as default value.
Try by assigning some value in variable 'sampleValue' and look at output, its changed (overwrite) by newer one. Look at image below.
Consider in C# Language
Let's take a look at example given below in C# Language, it has a main method having an unassigned variable named 'price' but when we run this, a 'compile-time error' comes out. Look at image given below.
Try by assigning some value in variable 'price' and look at output, error is fixed. Look at image below.
So, finally at the end we got following points.
(i) A variable must be definitely assigned at each location where its value is obtained.
(ii) A variable must be definitely assigned at each location where it is passed as a reference parameter.
(iii) All output parameters of a function member must be definitely assigned at each location where the function member returns.
(iv) The 'this' variable of a 'struct-type' instance constructor must be definitely assigned at each location where that instance constructor returns.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples