Inside .Net readonly

The common language runtime in .Net Framework supports two kind of fields – readonly and read/write fields. As name suggests, value in the read/write fields can be assigned as many times as one wants; On the other hand, value in the readonly field can not be changed after it get initialized in type/instance contructor of the type containing the readonly.

Depending on the type of the readonly field – static/intance– it gets initialized. Static readonly gets loaded when the dll containing the class being loaded by CLR where as  instance readonly field got initialized when the constructor get called for the particular instance. In the following code – Bullet1 gets initialized when the InsideReadonly first gets loaded in CLR –

public class InsideReadonly

     public static readonly string Bullet1 = “\u2022”;


Whereas Bullet1 gets initialized when InsideReadonly readonlyObject = new InsideReadonly(); line get executed –

public class InsideReadonly
     public readonly string Bullet1 = “\u2022”;

The versioning problem that I discussed in my last post- Inside .Net Constants( can be easily solved by using one of the above code block replacing the constant with readonly. Changing the value of the readonly field Bullet1 with a new value and building the .dll makes the application load the new values , given that versioning policy of the .DLL assembly always add the newer version / the assembly is not strongly typed.

By saying all these, I would like to make one point about the readonly fields – whenever we want to use it – we need to keep in mind that, the value of the readonly field only can be ONLY assigned in either in variable declaration or in type/instance constructor –  

public class InsideReadonly
            public readonly string Bullet1 = “\u2022”;            
public InsideReadonly()
                Bullet1 = “Changed Bullet1”;//Allowed                
Bullet1 = “Changed Bullet11111”;//Allowed
            public void TestChangeReadonly()
                Bullet1 = “Change is not allowed”;// Not allowed

Inside .Net Constants

By definition, constants are fixed numbers or values which represent the universal facts. When comes to programming language, it represents the same analogy- symbol with “Never-Changing Value”. In .Net Framework, constant(const) represent a symbol which contain a fixed/never changing value. Defining a constant in C# – 

           public const string Bullet = “\u2022”; 

We can use any primitive types supported in .Net Framework to define constant.   When we define a constant, the symbol is stored in the module’s metadata in compile time and compiler gets its value and copies it to the emitted IL code generated. In short, const value is directly embedded inside the code.           

Some facts about .Net const:

1.       Value of the const is decided in compile time. 
2.       We can only define const for primitive type.
3.       const are saved in the module’s metadata which then extracted and emitted in the IL code generated during compile time.
4.       Since there is no memory address is allocated for the constant – we can’t pass a const by reference. Therefore, it does not have good cross-module versioning usability. I will come back to this point.
5.       const symbol’s value never changes. That’s why, const symbols are associated with the .Net Type rather than instances.

Design consideration while using const: 

const should only be used when it is known that it’s value will never change, as I mentioned in the definition– universal fact. J For example – I defined here a const that represented the Unicode of the Character Bullet which kind of an Universal fact and will never change. Now, if we define const symbol that changes [I think which needs a code reviewJ], the problem that we might face is Cross-Module versioning. Let’s check out the following code which resides in a .dll –   public class ConnectionStrings
public const string UserDbConnectionString = “…”;

And we are using
ConnectionStrings class by adding reference of the .dll in our application. As we already know, the const symbol’s value  just emitted in the IL code and UserDbConnectionString const actually don’t need any Memory allocation, which makes the .dll file not being loaded at runtime. The value of UserDbConnectionString is already copied from the module’s metadata to our application’s generated IL. We can simply delete the .dll file and it should work accordingly.

There is no problem in so far. However, due to some reason, the value of the UserDbConnectionString get changed [ May be due to the deployment issue.]. Now we build the dll. How come the change is not reflected in our application’s code ? J Dude, we need to re-build our application as well. L 

To state the whole Versioning things in short – we need to keep into consideration while we define a constant symbol in our module whether the symbol will be referenced across the module. If the const symbol does not need any cross-module reference – then we should go for const otherwise, we need to change the implementation, For the above mentioned example I would change the const to readonly –   public class ConnectionStrings
      public readonly string UserDbConnectionString = “…”;

Lunch breakJ. I will try to post on readonly later on.

Converting UTF8 Encoded String to Bytes[]

I think every developer faced this problem of converting Unicode encoded string to Bytes[] . But .Net Framework has a very rich support for converting Encoded String to Bytes[].  .Net Framework support following 4 Encoding which is inherited from Base class Encoding (For Details – )

1.       System.Text.ASCIIEncoding – Encodes characters as 7Bit ASCII character

2.       System.Text.UnicodeEncoding – Encode characters in 2 consecutive Bytes enabling support for Big Endean or Little Endean.

3.       System.Text.UTF7Encoding – Encode characters in UTF7

4.       System.Text.UTF8Encoding-– Encode characters in UTF8

Now, let’s consider our text to be UTF8 encoded like

_TextBuilder = new StringBuilder(223);
_TextBuilder.AppendFormat(@”<?xml version=””1.0″” encoding=””UTF-8″”?>{0}”, Environment.NewLine);
            _TextBuilder.AppendFormat(@”<Contents Type=””string””><![CDATA[• das sfas fdasfs afdasfasd fasd hg kjh klhhjn “);           
_TextBuilder.AppendFormat(@”fdhæfdhj fdh.lfjnhfjk.lnh fdæjlf hlæfjhnf læhfj hglæjælfdh{0}”, Environment.NewLine);
_TextBuilder.AppendFormat(@”hfdj  fdklhjfdh]]></Contents>”);
string pdfDirectorXml = _TextBuilder.ToString();

The String pdfDirectorXml contains some unicode charecters with classic Bell Charecter also.The easiest way to convert UTF8 encoded text to Binary –

encoding = new UTF8Encoding();
      byte[] bytes = encoding.GetBytes(pdfDirectorXml);

Hence, you can get the UTF-8 encoded byte[] representation of the string. J