What is the difference between typeof(), GetType() and IS in C# and VB.NET

What is the difference between typeof(), GetType() and is?

  • typeof() takes a type name specified at compile Time.
  • GetType() gets the Type of an Object at runtime
  • is returns true if an instance is in the inheritance tree. Since the is Keyword is casting the object, you should use it with care.
  • here is an example.

    class Employee { } 
    class Developer : Employee { }
    
    void PrintTypes(Employee e) { 
        print(e.GetType() == typeof(Employee)) // false 
        print(e is Employee)                   // true 
        print(e.GetType() == typeof(Developer))    // true
    }
    

    How to enumerate an Enum in C# and VB.NET

    To enumerate an Enum in C# and VB.NET you can use the snippet below.

    Sample C#

    public enum TestEnum
    {
    	These = 0,
    	Are = 1,
    	Sample = 2,
    	Enums = 3,
    	Duplicates = 3,
    	Included = 4
    }
    
    static void Main(string[] args)
    {
    	foreach (var testEnum in Enum.GetNames(typeof(TestEnum)))
    	{
    		System.Console.WriteLine(testEnum);
    	}
    	Console.Read();
    }
    

    Sample VB.NET

    Public Enum TestEnum
    	These = 0
    	Are = 1
    	Sample = 2
    	Enums = 3
    	Duplicates = 3
    	Included = 4
    End Enum
    
    Private Shared Sub Main(args As String())
    	For Each testEnum As var In [Enum].GetNames(GetType(TestEnum))
    		System.Console.WriteLine(testEnum)
    	Next
    	Console.Read()
    End Sub
    

    How to get return Value from method invocation using reflection in C# and VB.NET

    To get return Value from method invocation using reflection in C# and VB.NET you can use the snippet below.

    Sample C#

    var returnValue = (Int32)methodInfo.Invoke(null,null); //just cast the returned object of Invoke to the needed Type. Theres no difference if it is a static method/class or not
    

    Sample VB.NET

    Dim returnValue = DirectCast(methodInfo.Invoke(Nothing, Nothing), Int32) 'just cast the returned object of Invoke to the needed Type. Theres no difference if it is a static method/class or not
    

    For more informations on how to invoke methods from other assemblies using reflection see:

  • How to call a static method in different assembly using Reflection in C# and VB.NET
  • How to call a non-static method in different assembly using Reflection in C# and VB.NET
  • How to get the size of all tables in MSSQL

    To get the size of all tables using MSSQL you can use the snippet below.

    Sample MSSQL

    SELECT 
        tab.NAME AS [Tablename],
        s.Name AS [Schema Name],
        part.rows AS [Count of Rows],
        SUM(a.total_pages) * 8 AS [Total Space in KB], 
        SUM(a.used_pages) * 8 AS [Used Space in KB], 
        (SUM(a.total_pages) - SUM(a.used_pages)) * 8  AS [Unused Space in KB]
    FROM sys.tables tab
    INNER JOIN sys.indexes idx ON tab.OBJECT_ID = idx.object_id
    INNER JOIN sys.partitions part ON idx.object_id = part.OBJECT_ID AND idx.index_id = part.index_id
    LEFT OUTER JOIN sys.schemas s ON tab.schema_id = s.schema_id
    INNER JOIN sys.allocation_units a ON part.partition_id = a.container_id
    WHERE tab.NAME NOT LIKE 'dt%' AND tab.is_ms_shipped = 0 AND idx.OBJECT_ID > 255 
    GROUP BY tab.Name, s.Name, part.Rows
    ORDER BY 4 DESC
    

    How to check if a number is a power of 2 in C# and VB.NET

    To check if a number is a power of 2 in C# and VB.NET you can use the following extension method.

    Sample C#

    public static bool IsPowerOfTwo(this ulong input)
    {
        return (input != 0) && ((input & (input - 1)) == 0);
    }
    

    Sample VB.NET

    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function IsPowerOfTwo(input As ULong) As Boolean
    	Return (input <> 0) AndAlso ((input And (input - 1)) = 0)
    End Function
    

    As always, the extension method was added to out Fesslersoft.Extensions library @Github

    How to get monday date of current week in MSSQL

    To get the Monday date of the current week you can use the snippet below.

    SELECT DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 0) AS Monday
    

    How to get the type of a generic parameter in C# and VB.NET

    To get the type of a generic parameter in C# and VB.NET you can use the following snippet.

    Sample C#

    Type typeParam = typeof(T);
    

    Sample VB.NET

    Dim typeParam As Type = GetType(T)
    

    How to get all column names of a Table in Oracle

    To get all column names of a Table in Oracle you can use the following snippet.

    SELECT table_name, column_name, data_type, data_length
    FROM USER_TAB_COLUMNS
    WHERE table_name = 'TABLENAME'
    

    If you are using MSSQL, take a look at this snippet -> How to list all columns from a table in MSSQL

    How to get the Youtube VideoId from Url in C# and VB.NET

    To get the Youtube VideoId from an Url in C# and VB.NET you can use the following snippet.
    It matches these 18 type of Youtube Links (Sample Data):

    Sample Input

  • http://youtu.be/AAAAAAAAA01
  • http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02
  • http://www.youtube.com/embed/watch?v=AAAAAAAAA03
  • http://www.youtube.com/embed/v=AAAAAAAAA04
  • http://www.youtube.com/watch?v=AAAAAAAAA06
  • www.youtube.com/watch?v=AAAAAAAAA07
  • www.youtu.be/AAAAAAAAA08
  • youtu.be/AAAAAAAAA09
  • http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05
  • http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related
  • http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17
  • http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0
  • youtube.com/watch?v=AAAAAAAAA10
  • http://www.youtube.com/watch/AAAAAAAAA11
  • http://www.youtube.com/v/AAAAAAAAA12
  • http://www.youtube.com/v/AAAAAAAAA13
  • Sample C#

    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace de.fesslersoft.YoutubeRegexTest
    {
        internal static class Youtube
        {
            private const string YoutubeLinkRegex = "(?:.+?)?(?:\\/v\\/|watch\\/|\\?v=|\\&v=|youtu\\.be\\/|\\/v=|^youtu\\.be\\/)([a-zA-Z0-9_-]{11})+";
    
            internal static string GetVideoId(string input)
            {
                var regex = new Regex(YoutubeLinkRegex, RegexOptions.Compiled);
                foreach (Match match in regex.Matches(input))
                {
                    //Console.WriteLine(match);
                    foreach (var groupdata in match.Groups.Cast<Group>().Where(groupdata => !groupdata.ToString().StartsWith("http://") && !groupdata.ToString().StartsWith("https://") && !groupdata.ToString().StartsWith("youtu") && !groupdata.ToString().StartsWith("www.")))
                    {
                        return groupdata.ToString();
                    }
                }
                return string.Empty;
            }
        }
    }
    

    Sample VB.NET

    Imports System.Linq
    Imports System.Text.RegularExpressions
     
    Namespace de.fesslersoft.YoutubeRegexTest
        Friend NotInheritable Class Youtube
            Private Sub New()
            End Sub
            Private Const YoutubeLinkRegex As String = "(?:.+?)?(?:\/v\/|watch\/|\?v=|\&v=|youtu\.be\/|\/v=|^youtu\.be\/)([a-zA-Z0-9_-]{11})+"
     
            Friend Shared Function GetVideoId(input As String) As String
                Dim regex = New Regex(YoutubeLinkRegex, RegexOptions.Compiled)
                For Each match As Match In regex.Matches(input)
                    For Each data As Group In match.Groups.Cast(Of Group)().Where(Function(groupdata) Not groupdata.ToString().StartsWith("http://") AndAlso Not groupdata.ToString().StartsWith("https://") AndAlso Not groupdata.ToString().StartsWith("youtu") AndAlso Not groupdata.ToString().StartsWith("www."))
                        Return data.ToString()
                    Next
                Next
                Return String.Empty
            End Function
        End Class
    End Namespace
    

    Output / Sample

    var urlList = new List<String>
    {
    	"http://youtu.be/AAAAAAAAA01",
    	"http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02",
    	"http://www.youtube.com/embed/watch?v=AAAAAAAAA03",
    	"http://www.youtube.com/embed/v=AAAAAAAAA04",
    	"http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05",
    	"http://www.youtube.com/watch?v=AAAAAAAAA06",
    	"www.youtube.com/watch?v=AAAAAAAAA07",
    	"www.youtu.be/AAAAAAAAA08",
    	"youtu.be/AAAAAAAAA09",
    	"youtube.com/watch?v=AAAAAAAAA10",
    	"http://www.youtube.com/watch/AAAAAAAAA11",
    	"http://www.youtube.com/v/AAAAAAAAA12",
    	"http://www.youtube.com/v/AAAAAAAAA13",
    	"http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related",
    	"http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17",
    	"http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0"
    };
    
    foreach (var entry in urlList)
    {
    	Console.WriteLine(Youtube.GetVideoId(entry));
    }
    Console.Read();
    

    will result in the follwing output:

    Youtube VideoId Regex Console Window Output

    Youtube VideoId Regex Console Window Output

    A simpler but less matching solution can be found here: How to get the VideoID of a youtube video using Regex