.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, 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 using 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 the field is set at run time and can thus be modified by the containing class, whereas the value of a const the field is set to a compile-time constant.

What is a static constructor?

It is a special type of constructor, introduced with C#. It gets called before creating 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 inheritances?

No, Use interface

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

System. A string is an 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?

Process of creating different implementation of a method having the same name as a base class in a derived class. It implements Inheritance.
When we need to provide a different implementation than the provided by the base class, We define the same method with the same signatures in the derived class. The 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 the base class and not overrideable, we need to provide a different implementation. This process is known as shadowing, uses shadows/new keyword.

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم