.NET programming Questions and Answers
.NET is a common purpose programming platform. It can be used for any workload or any sort of application where general purpose solutions are used. Questions include code examples that enough to understand the problems.

Skater .NET Obfuscator
More about Skater .NET Obfuscator
Download Skater .NET Obfuscator
Order Skater .NET Obfuscator

  • How to fix NullReferenceException?
  • Sometimes you have C# code and when it runs, it throws a NullReferenceException with the following error message: "Object reference not set to an instance of an object" What does this mean? How can we handle that?

  • Update the GUI from another thread
  • What is the easiest way to update a Label control on a form from another thread in C#?

  • Random number generator generats only one random number
  • Random does not make any guarantees of thread-safety. To prevent that we may synchronize so that we do not access it at the same time from different threads, or use different Random instances per thread.

  • How to use the reflection to call a generic method?
  • Sometimes we have to figure out a right way to call a generic method when the type parameter is not known at compile time, but instead is obtained dynamically at runtime.

  • Properly clean up Excel interop objects
  • In your .NET app the Excel interop process is still in the background even after you close Excel. It is only released once your .NET application is closed manually.

  • Control accessed from a thread other than the thread it created on since Cross-thread operation not valid
  • Sometimes when you are trying to use multi-threading in a winforms app so that while it is running a long process, UI would get locked up. However after the task has finish and it try to update the UI you may get the error: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on when you try to execute a C# windows application.

  • Clone or deep copy an object
  • We are creating a child object of some data type object. How to make possible to clone / deep copy an object so that the deep copied object can be modified without any changes being reflected in the initial object?

  • Create Excel (.XLS and .XLSX) file using C#
  • Create an Excel Spreadsheet in .NET without requiring Excel to be installed on the PC that is executing the application.

  • The actual problem with mutable structs
  • Mutable objects usually have multiple properties. Is this an actual problem with C# structs mutability?

  • Convert Hexadecimal String to Byte Array, and vice versa
  • Any hex string that validly represents a byte array must have an even character count. Using Substring is the best option in combination with Convert.ToByte.

  • IndexOutOfRangeException and how to fix it?
  • Some .NET app code when executes gives you an IndexOutOfRangeException, with the message: "Index was outside the bounds of the array". What does this mean? How can you handle that?

  • Is Application.DoEvents() useful in C#?
  • Can we use the Application.DoEvents() in C#? Is this function a method to allow the GUI to catch up with the whole .NET application?

  • Dynamic LINQ OrderBy on IEnumerable<T>
  • You will need the dynamic LINQ library to implement LINQ ordering functionality on IEnumerable<T>.

  • How to encrypt and decrypt a string?
  • The troublesome part about string encryption actually deals with the keys and not the algorithms. You should be worry about where you store your keys, and if you have to, how you exchange them.

  • Send email in .NET via a public email account like Yahoo or Gmail
  • Instead of sending emails from your host, you may suggest of sending your email messages though a public account (Gmail, Yahoo, etc.). How to implement such emailing jobs?

  • The difference between String and string in C#
  • What is the differences between: string s = "Hello world!"; and String S = "Hello world!";? What are the directions for the use of each?

  • How to use the IDisposable interface correctly?
  • The main use of the IDisposable interface is to clean up unmanaged resources.

  • How to check if a file is in use?
  • Sometimes you are in need to repeatedly regenerate, access, and then close the same binary temp file. Usually it works without problem. However if PC runs slow, it will try to access the file before it has been stored back to the hard drive with the following error message: "File in use by another process".



    How to fix NullReferenceException? Sometimes you have C# code and when it runs, it throws a NullReferenceException with the following error message: "Object reference not set to an instance of an object" What does this mean? How can we handle that?

    A NullReferenceException occurs when you try to use a method or property of a reference type (C#, Visual Basic) whose value is null. For example, you may have tried to use an object without first using the new keyword (New in Visual Basic), or tried to use an object whose value was set to null (Nothing in Visual Basic).

    Common causes of NullReferenceExceptions
    Any reference type variable can be null. Local variables, the properties of a class, method parameters, and method return values can all contain a null reference. Calling methods or properties of these variables when they are null causes a NullReferenceException. Specific cases:

  • A local variable or member field is declared but not initialized
  • A property or field is null
  • A method parameter is null
  • The return value of a method is null
  • An object in a collection or array is null
  • An object is not created because of a condition
  • An object passed by reference to a method is set to null



  • Update the GUI from another thread What is the easiest way to update a Label control on a form from another thread in C#?

    Run the following code:

    using System;
    using System.Windows.Forms;

    public static class ControlExtensions
    {
    /// <summary>
    /// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread.
    /// </summary>
    /// <param name="control"></param>
    /// <param name="code"></param>
    public static void ThreadCall(this Control @this, Action code)
    {
    if (@this.InvokeRequired)
    {
    @this.BeginInvoke(code);
    }
    else
    {
    code.Invoke();
    }
    }
    }


    Then call that by using the following code:


    this.ThreadCall(() => this.Label1.Text = "Write New Text Here");




    Random number generator generats only one random number Random does not make any guarantees of thread-safety. To prevent that we may synchronize so that we do not access it at the same time from different threads, or use different Random instances per thread.

    Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the initial instance.


    // Procedure to create random number
    private static readonly Random random = new Random();
    private static readonly object syncLock = new object();
    public static int RandomNumber(int min, int max)
    {
    lock(syncLock) { // synchronize
    return random.Next(min, max);
    }
    }


    So
    Next is going to change the internal state of the Random instance. If we do that at the same time from multiple threads, you may reason "I just have made the output even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random does not make any guarantees of thread-safety.




    How to use the reflection to call a generic method? Sometimes we have to figure out a right way to call a generic method when the type parameter is not known at compile time, but instead is obtained dynamically at runtime.

    What is the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?
    Consider the following sample code: within the
    Example() function, what is the most concise way to invoke GenericMethod<T>() using the Type stored in the newType param?


    public class Sample
    {
    public void Example(string typeName)
    {
    Type newType = FindType(typeName);

    // What goes here to call GenericMethod<T>()?
    GenericMethod<newType>(); // It does not work

    // What changes to call StaticMethod<T>()?
    Sample.StaticMethod<newType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
    // ...
    }

    public static void StaticMethod<T>()
    {
    //...
    }
    }


    You need to use reflection to get the method to start with, then create that by sending type params with MakeGenericMethod:


    MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
    MethodInfo generic = method.MakeGenericMethod(myType);
    generic.Invoke(this, null);


    For a static method, pass
    null as the first argument to Invoke. That is nothing to do with generic methods cause that is a normal reflection.



    Properly clean up Excel interop objects In your .NET app the Excel interop process is still in the background even after you close Excel. It is only released once your .NET application is closed manually.

    Excel does not quit because .NET application is still holding references to COM objects. When your app is invoking at least one member of a COM object without assigning it to a variable. In the following code the excelApp.Worksheets object which is directly used without assigning it to a variable:


    Worksheet sheet = excelApp.Worksheets.Open(...);
    ...
    Marshal.ReleaseComObject(sheet);


    The .NET code internally created a wrapper for the Worksheets COM object which did not get released by the code and was the cause why Excel was not unloaded.
    The
    sheets variable in the code below has a COM reference that will not be released until its garabage was collected. The rule is: never use 2 dots with com objects! Always create a sheet, and call ReleaseComObject() on the sheets.


    Worksheets sheets = excelApp.Worksheets; // assign a variable
    Worksheet sheet = sheets.Open(...);
    ...
    Marshal.ReleaseComObject(sheets);
    Marshal.ReleaseComObject(sheet);



    Control accessed from a thread other than the thread it created on since Cross-thread operation not valid Sometimes when you are trying to use multi-threading in a winforms app so that while it is running a long process, UI would get locked up. However after the task has finish and it try to update the UI you may get the error: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on when you try to execute a C# windows application.

    Please use an extension method and lambdas to make your code much cleaner.


    using System.ComponentModel; public static class ISynchronizeInvokeExtensions
    {
    public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
    {
    if (@this.InvokeRequired)
    {
    @this.Invoke(action, new object[] { @this });
    }
    else
    {
    action(@this);
    }
    }
    }

    Now please use InvokeEx on any ISynchronizeInvoke and be able to access the properties and fields of implementing class.


    this.InvokeEx(f => f.listView1.Items.Clear());



    Clone or deep copy an object We are creating a child object of some data type object. How to make possible to clone / deep copy an object so that the deep copied object can be modified without any changes being reflected in the initial object?

    One way to guarantee that an object will be cloned exactly how you want it is to manually clone every field in the object. The disadvantage to this method is it's tedious and error prone: if you add or change a field in the class, chances are you will forget to update the Clone method. Note that care must be taken to avoid an infinite loop when cloning referenced objects that may refer back to the original object. Here is a simple example that performs a deep copy:


    public class Person : ICloneable{
    public string Name;
    public Person Spouse;
    public object Clone()
    {
    Person p = new Person();
    p.Name = this.Name;
    if (this.Spouse != null)
    p.Spouse = (Person)this.Spouse.Clone();
    return p;
    }
    }


    Another way is to Clone with
    MemberwiseClone. MemberwiseClone is a protected method in the Object class that creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. For value-type fields, this performs a bit-by-bit copy. For reference-type fields, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object. Note this works for all derived classes, and hence you only need to define the Clone method once in the base class. Take a look at the simple code below:


    public class Person : ICloneable{
    public string Name;
    public Person Spouse;
    public object Clone()
    {
    return this.MemberwiseClone();
    }
    }



    Create Excel (.XLS and .XLSX) file using C# Create an Excel Spreadsheet in .NET without requiring Excel to be installed on the PC that is executing the application.

    To create an Excel Spreadsheet in .NET we recommend to use Rustemsoft's XMLFox conversion module with command-line interface.
    XMLFox conversion module (XMLFoxCmd) is a data conversion software lets users to interactively create XML data transformation. It allows you to use XML documents by exporting it to several other data formats. It is used for quickly building application integration solutions. It will allow you to map and integrate some types of data stored in XML document in a user-friendly command-line interface.

    Also you may use Open XML SDK 2.0 for Microsoft Office

    The most important benefits:
    That does not require MS Office to be installed on your PC
    Since it made by Microsoft it supported by the decent MSDN documentation
    You will need a just one .NET dll to use in your project
    Open XML SDK comes with many tools like: diff, validator, etc.

    Links:
    Download SDK
    Main MSDN Landing
    How Do I...



    The actual problem with mutable structs Mutable objects usually have multiple properties. Is this an actual problem with C# structs mutability?

    Consider this code which is trying to mutate a readonly mutable struct. What the output is expected to be?


    struct Mutable {
    private int x;
    public int Mutate() {
    this.x = this.x + 1;
    return this.x;
    }
    }

    class Test {
    public readonly Mutable m = new Mutable();
    static void Main(string[] args) {
    Test t = new Test();
    System.Console.WriteLine(t.m.Mutate());
    System.Console.WriteLine(t.m.Mutate());
    System.Console.WriteLine(t.m.Mutate());
    }
    }

    This code will print 1, 1, 1. Because accessing a value type gives you a copy of the value. When you say t.m, you get a copy of whatever is presently stored in m. The m is immutable, but the copy is not. The copy is then mutated, and the value of x in the copy is returned. But m remains non-modified. This is yet another reason why mutable value types are evil. Try to always make value types immutable.



    Convert Hexadecimal String to Byte Array, and vice versa Any hex string that validly represents a byte array must have an even character count. Using Substring is the best option in combination with Convert.ToByte.

    It is easy. First, Byte Array to String:


    public static string ByteArrayToString(byte[] ba)
    {
    string hex = BitConverter.ToString(ba);
    return hex.Replace("-","");
    }


    Revers conversion, String to Byte Array:


    public static byte[] StringToByteArray(String hex)
    {
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
    }



    IndexOutOfRangeException and how to fix it? Some .NET app code when executes gives you an IndexOutOfRangeException, with the message: "Index was outside the bounds of the array". What does this mean? How can you handle that?

    The exception's error message says that you are trying to access a collection item by its index, using an invalid index. An index number value is incorrect when it is greater than (or equal) the collection's number of elements it contains or lower than to the collection?s lower bound. For example you have declared an array as:


    string[] stringArray = new string[5];

    You can access the string array from 0 to 4. Any numeric values outside this range will generate the IndexOutOfRangeException. Do not forget that when you declare and access an array in your code.



    Is Application.DoEvents() useful in C#? Can we use the Application.DoEvents() in C#? Is this function a method to allow the GUI to catch up with the whole .NET application?

    The usage of Application.DoEvents is an indication of a bad .NET application design. You should consider to do some code in separated threads instead.
    You may call the static
    DoEvents method on the Application class in the System.Windows.Forms namespace. Application.DoEvents() is used to pump messages in the UI thread when performing a long-running task in the UI thread. This is almost always not the best way to do things. The better solution would be to do all of your application interface actions on another thread, and then run the Invoke method on a control, passing a delegate to update the UI when necessary. This will cause a message to be sent to the UI thread to update itself, but since you are handling all of the processing on the other thread, it should be updated immediately.



    Dynamic LINQ OrderBy on IEnumerable<T> You will need the dynamic LINQ library to implement LINQ ordering functionality on IEnumerable<T>.

    Make a reference to the System.Linq.Dynamic.dll library. Then put the using System.Linq.Dynamic; declaration into the declarative region in which the using declarations appear in your .NET code. To code the LINQ ordering functionality write down in your code something like the following:
    cars = cars.AsQueryable().OrderBy("Make ASC, Year DESC").ToList();

    If you are going to do the ordering without the dynamic LINQ library, you will need to implement the below code. This covers most common scenarios including nested properties. To get it working with
    IEnumerable<T> you could add some wrapper methods that go via AsQueryable, but the presented code is the core Expression logic needed.


    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
    {
    return ApplyOrder<T>(source, property, "OrderBy");
    }
    public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
    {
    return ApplyOrder<T>(source, property, "OrderByDescending");
    }
    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
    {
    return ApplyOrder<T>(source, property, "ThenBy");
    }
    public static IOrderedQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
    {
    return ApplyOrder<T>(source, property, "ThenByDescending");
    }
    static IOrderedQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName) {
    string[] props = property.Split('.');
    Type type = typeof(T);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = arg;
    foreach(string prop in props) {
    // use reflection (not ComponentModel) to mirror LINQ
    PropertyInfo pi = type.GetProperty(prop);
    expr = Expression.Property(expr, pi);
    type = pi.PropertyType;
    }
    Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
    LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);

    object result = typeof(Queryable).GetMethods().Single(
    method => method.Name == methodName
    && method.IsGenericMethodDefinition
    && method.GetGenericArguments().Length == 2
    && method.GetParameters().Length == 2)
    .MakeGenericMethod(typeof(T), type)
    .Invoke(null, new object[] {source, lambda});
    return (IOrderedQueryable<T>)result;
    }



    How to encrypt and decrypt a string? The troublesome part about string encryption actually deals with the keys and not the algorithms. You should be worry about where you store your keys, and if you have to, how you exchange them.

    We will not bother and go deep into the jungle. We will just show you how to decrypt and encrypt a string by using a wrapper object to access the cryptographic service provider (CSP) version of the Data Encryption Standard (DES) algorithm.


    public string EncryptString(string inputString){
    MemoryStream ms = null;
    try{
    byte[] IV = {12, 43, 67, 27, 17, 21, 57, 35};
    string encryptKey = "password"; // 8 characters key
    byte[] key = {};
    key = Encoding.UTF8.GetBytes(encryptKey);
    byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
    DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
    ms = new MemoryStream();
    ICryptoTransform transform = provider.CreateEncryptor(key, IV);
    CryptoStream cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write);
    cryptoStream.Write(byteInput, 0, byteInput.Length);
    cryptoStream.FlushFinalBlock();
    }
    catch (Exception ex){
    Response.Write(ex.Message);
    }
    return Convert.ToBase64String(ms.ToArray());
    }

    public string DecryptString(string inputString){
    MemoryStream ms = null;
    try{
    byte[] IV = {12, 43, 67, 27, 17, 21, 57, 35};
    string decryptKey = "password"; // 8 characters key
    byte[] key = {};
    key = Encoding.UTF8.GetBytes(decryptKey);
    byte[] byteInput = new byte[inputString.Length];
    byteInput = Convert.FromBase64String(inputString);
    DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
    ms = new MemoryStream();
    ICryptoTransform transform = provider.CreateDecryptor(key, IV);
    CryptoStream cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write);
    cryptoStream.Write(byteInput, 0, byteInput.Length);
    cryptoStream.FlushFinalBlock();
    }
    catch (Exception ex){
    Response.Write(ex.Message);
    }
    Encoding encoding1 = Encoding.UTF8;
    return encoding1.GetString(ms.ToArray());
    }



    Send email in .NET via a public email account like Yahoo or Gmail Instead of sending emails from your host, you may suggest of sending your email messages though a public account (Gmail, Yahoo, etc.). How to implement such emailing jobs?

    Use Gmail Smtp client which allows you to send email messages by using SMTP Protocol.


    using System;
    using System.Net;
    using System.Net.Mail;

    static void SendMail(){
    // Sender's gmail address
    string fromAddress = "Sender@gmail.com";
    // Receiver's gmail address
    string toAddress = "Receiver@yahoo.com";
    const string SendersPassword = "Password";
    const string subject = "Subject";
    // Message content
    const string body = "Hello!";

    try{
    // Gmail SMTP server name is smtp.gmail.com and port number is 587
    SmtpClient smtp = new SmtpClient{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress, SendersPassword),
    Timeout = 3000
    };
    MailMessage message = new MailMessage(fromAddress, toAddress, subject, body);
    // Send the message
    smtp.Send(message);
    Console.WriteLine("Message has been sent");
    }
    catch (Exception ex){
    Console.WriteLine(ex.Message);
    }
    }



    The difference between String and string in C# What is the differences between: string s = "Hello world!"; and String S = "Hello world!";? What are the directions for the use of each?

    The string is an alias in C# for System.String. So technically, there is no difference.
    So the
    String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in MSIL (Intermediate Language), so there is no difference. Choose what you like and use that.
    We can mention the same about (int, System.Int32)

    Howevere... :)

    string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.
    If for some reason you wanted a variable called
    string, you would see only the first of these compiles:


    StringBuilder String = new StringBuilder(); // compiles
    StringBuilder string = new StringBuilder(); // does not compile

    If you really want a variable name called string you can use @ as a prefix:


    StringBuilder @string = new StringBuilder();



    How to use the IDisposable interface correctly? The main use of the IDisposable interface is to clean up unmanaged resources.

    IDisposable is often used to operate the using statement and take advantage of an easy way to do deterministic cleanup of managed objects.


    public class LogContext : IDisposable {
    public EnteringLog(string enterID) {
    Console.WriteLine("Entering Log Context {0}", enterID);
    Log.Indent();
    }
    public void Dispose() {
    Log.Outdent();
    }
    public static void Main() {
    Console.WriteLine("Your initial stuff");
    try {
    using(new LogContext()) {
    Console.WriteLine("Your stuff inside the context");
    throw new Exception();
    }
    } catch {
    Console.WriteLine("An exception got from inside a child logging context");
    } finally {
    Console.WriteLine("Your final stuff");
    }
    }
    }



    How to check if a file is in use? Sometimes you are in need to repeatedly regenerate, access, and then close the same binary temp file. Usually it works without problem. However if PC runs slow, it will try to access the file before it has been stored back to the hard drive with the following error message: "File in use by another process".

    You can accomplish that creating checks by using exception handling only.


    static bool FileInUse(string path)
    {
    try
    {
    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
    {
    fs.CanWrite
    }
    return false;
    }
    catch (IOException ex){
    return true;
    }
    }

    string filePath = "C:\\Documents Folder\\FileName";
    bool isFileInUse;

    isFileInUse = FileInUse(filePath);

    // Do File checking here
    if (isFileInUse)
    Console.WriteLine("File is in use");
    else
    Console.WriteLine("File is not in use");

    About Rustemsoft

    Rustemsoft LLC is a creative ISV (Independent Software Vendor) specializes in intelligent software solutions for Xcode programmers, XML designers, and .NET developers. Rustemsoft provides comprehensive programming solutions that improve productivity, profitability and result in superior software development and design.

    Copyright © 2001-2024 Rustemsoft LLC

    Skater .NET Obfuscator

    TouchControls iOS Framework

    XMLFox

    Home

    Products

    Downloads

    Articles

    Company

    Support