What is the difference between mutable and immutable in C# and VB.NET

What is the difference between a mutable and immutable string in C# and VB.NET?

  • A mutable string can be changed.
  • An immutable string cannot be changed.
  • Mutable is the english word for can change. Immutable is the english word for cannot change.

    if you alter a String, you are creating a new string object internally. So String is immutable. If you alter a StringBuilder no new Objects are created internally so, StringBuilder is mutable.

    IsNull extension method for C# and VB.NET

    You can use the IsNull Extension method by using the snippet below.

    Sample C#

    public static bool IsNull(this object source)
    {
         return source == null;
    }
    

    Sample VB.NET

    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function IsNull(source As Object) As Boolean
    	Return source Is Nothing
    End Function
    

    As always, this extension method has been added to the Github Fesslersoft.Extensions Repository

    How to set a Property Value by Name in C# and VB.NET

    To set a Property Value by Name in C# and VB.NET you can use the following snippet.

    Sample C#

    public static bool SetPropertyByName(this Object obj, string name, Object value)
    {
    	var prop = obj.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
    	if (null == prop || !prop.CanWrite) return false;
    	prop.SetValue(obj, value, null);
    	return true;
    }
    

    Sample VB.NET

    Public Shared Function SetPropertyValueByName(obj As [Object], name As String, value As [Object]) As Boolean
    	Dim prop = obj.[GetType]().GetProperty(name, BindingFlags.[Public] Or BindingFlags.Instance)
    	If prop Is Nothing OrElse Not prop.CanWrite Then
    		Return False
    	End If
    	prop.SetValue(obj, value, Nothing)
    	Return True
    End Function