Search Code Guru

.NET/C# Interview Questions - SET 1

How do I calculate an MD5 hash from a string

It is a common practice to store passwords in databases using a mixture. MD5 (defined in RFC 1321) is a standard hash algorithm, and using it from C# is easy.

Here’s an implementation of a method that converts a string to an MD5 hash, which is a 32-character string of hexadecimal numbers.

public string CalculateMD5Hash(string input)
{
  // step 1, calculate MD5 hash from input
  MD5 md5 = System.Security.Cryptography.MD5.Create();
  byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
  byte[] hash = md5.ComputeHash(inputBytes);

  // step 2, convert byte array to hex string
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < hash.Length; i++)
  {
      sb.Append(hash[i].ToString("X2"));
  }
  return sb.ToString();
}

An example call:

string hash = CalculateMD5Hash("abcdefghijklmnopqrstuvwxyz");

OUTPUT

C3FCD3D76192E4007DFB496CCA67E13B
To make the hex string use lower-case letters instead of upper-case, replace the single line inside the for loop with this line:

sb.Append(hash[i].ToString("x2"));

The difference is the ToString method parameter.

What is the difference between const and static readonly

The difference is that the value of a static read-only field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile-time constant.

What is static constructor?

It is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly). See the example below.

public class SomeClass()
{
	static SomeClass()
	{
		//Static members may be accessed from here
		//Code for Initialization
	}
}

Does C# support multiple inheritance?

No,Use interface

What is the difference between System. String and System.StringBuilder classes?

System.String is immutable, System.StringBuilder was designed to have a mutable string where a variety of operations can be performed.

Can you inherit multiple interfaces?

Yes, why not. Through Interface we can achieve

What-is-overriding?

Tprocess of creating different implementation of a method having a same name as base class, in a derived class. It implements Inheritance.
When we need to provide different implementation than the provide by base class, We define the same method with same signatures in the derived class. Method must be Protected/Protected-Friend/Public for this purpose. (Base class routine can be called by Mybase.Method, base.Method).

What is Shadowing?

When the method is defined as Final/sealed in base class and not override able and we need to provide different implementation for the same. This process is known as shadowing, uses shadows/new keyword.

Post a Comment

0 Comments