Definite Assignment Rule in C#


Introduction

In programming languages like C and C++, we can define a variable and then accidentally use it before initializing it. C and C++ languages have no in-built feature that can recognize that being done 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 using it; otherwise we will get a "compile-time" error.

Consider in C++ Language

Let's take a look at an example given below in C++ Language; it has a main method having an unassigned variable named "sampleValue" but when we run this, no error is issued. Even this display some value say it as default value.

image002.jpg

Try assigning a value in the variable "sampleValue" and look at the output, it has changed (overwritten) by the new value. Look at the image below.

image004.jpg

Consider in C# Language

Let's take a look at the example given below in the C# Language; it has a main method having an unassigned variable named "price" but when we run this, a "compile-time error" is issued. Look at the image given below.

image006.jpg

Try to assign a value to the ariable "price" and look at the output, an error is issued. Look at the image below.

image008.jpg

So, finally at the end we have the following points.

  1. A variable must be definitely assigned at each location where it's value is obtained.
  2. A variable must be definitely assigned at each location where it is passed as a reference parameter.
  3. All output parameters of a function member must be definitely assigned at each location where the function member returns.
  4. The "this" variable of a "struct-type" instance constructor must be definitely assigned at each location where that instance constructor returns.

 HAVE A HAPPY CODING!!


Recommended Free Ebook
Similar Articles