IsSmallerThan generic extension method for C# and VB.NET

This is the IsSmallerThan generic extension method, this extension method which is part of the Fesslersoft.Extensions. It should only work with numeric values.

Samples

Sample C#

Sample VB.NET


If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

IsLargerThan generic extension method for C# and VB.NET

This is the IsLargerThan generic extension method, this extension method which is part of the Fesslersoft.Extensions. It should only work with numeric values.

Samples

Sample C#

Sample VB.NET

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

How to get all Description Attributes of an Enum using C# or VB.NET

To get all Description Attributes of an Enum using C# or VB.NET you can use the snippet below.

Sample C# – Class

public class DescriptionAttributes<T>
    {
        protected List<DescriptionAttribute> Attributes = new List<DescriptionAttribute>();
        public List<string> Descriptions { get; set; }

        public DescriptionAttributes()
        {
            RetrieveAttributes();
            Descriptions = Attributes.Select(x => x.Description).ToList();
        }

        private void RetrieveAttributes()
        {
            foreach (var attribute in typeof(T).GetMembers().SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>()))
            {
                Attributes.Add(attribute);
            }
        }
    }

Usage C#

class Program
    {
        public enum TestEnum
        {
            [Description("An apple a day keeps the doctor away")]
            Apple=0,
            [Description("Yummie Strawberry")]
            Strawberry=1,
            [Description("Banana for scale")]
            Banana=2
        }

        static void Main(string[] args)
        {
            var descriptions = new DescriptionAttributes<TestEnum>().Descriptions.ToList();
            foreach (var description in descriptions)
            {
                Console.WriteLine(description);
            }
            Console.Read();
        }
    }

Sample VB.NET – Class

Public Class DescriptionAttributes(Of T)
	Protected Attributes As New List(Of DescriptionAttribute)()
	Public Property Descriptions() As List(Of String)
		Get
			Return m_Descriptions
		End Get
		Set
			m_Descriptions = Value
		End Set
	End Property
	Private m_Descriptions As List(Of String)

	Public Sub New()
		RetrieveAttributes()
		Descriptions = Attributes.[Select](Function(x) x.Description).ToList()
	End Sub

	Private Sub RetrieveAttributes()
		For Each attribute As var In GetType(T).GetMembers().SelectMany(Function(member) member.GetCustomAttributes(GetType(DescriptionAttribute), True).Cast(Of DescriptionAttribute)())
			Attributes.Add(attribute)
		Next
	End Sub
End Class

Usage VB.NET

Class Program
	Public Enum TestEnum
		<Description("An apple a day keeps the doctor away")> _
		Apple = 0
		<Description("Yummie Strawberry")> _
		Strawberry = 1
		<Description("Banana for scale")> _
		Banana = 2
	End Enum

	Private Shared Sub Main(args As String())
		Dim descriptions = New DescriptionAttributes(Of TestEnum)().Descriptions.ToList()
		For Each description As var In descriptions
			Console.WriteLine(description)
		Next
		Console.Read()
	End Sub
End Class

Result / Output

Enum Descriptions

Enum Descriptions

Generic Type Conversion snippet for C# and VB.NET

Here you can find a generic Type conversion snippet for C# and VB.NET.

Sample C#

public static T GenericConvert<T, X>(X value) where X : IConvertible
{
	return (T)Convert.ChangeType(value, typeof(T));
}

Sample VB.NET

Public Shared Function GenericConvert(Of T, X As IConvertible)(value As X) As T
	Return DirectCast(Convert.ChangeType(value, GetType(T)), T)
End Function

Dynamic Event Subscription using C# or VB.NET

The following snippet let you dynamically subscribe to events using C# or VB.NET.

Sample C#

//usage DynamicEventSubscription("button1", "Click", "button1_Click");
public void DynamicEventSubscription(string controlName,string eventName, string targetName, bool recursiveSearch=false)
{
	if (controlName == String.Empty) { throw new ArgumentNullException("controlName"); }
	if (eventName == String.Empty) { throw new ArgumentNullException("eventName"); }
	if (targetName == String.Empty) { throw new ArgumentNullException("targetName"); }

	try
	{
		var eventMethod = GetType().GetMethod(targetName);
		var control = Controls.Find(controlName, false).FirstOrDefault();
		if (control != null)
		{
			var eventToSubscribe = control.GetType().GetEvent(eventName);
			var handler = Delegate.CreateDelegate(eventToSubscribe.EventHandlerType, this, eventMethod);
			var button = Controls.Find(controlName, recursiveSearch).FirstOrDefault();
			eventToSubscribe.AddEventHandler(button, handler);
		}
	}
	catch (Exception ex)
	{
		//handle the exception your way
	}
}

Sample VB.NET

'usage DynamicEventSubscription("button1", "Click", "button1_Click")
Public Sub DynamicEventSubscription(controlName As String, eventName As String, targetName As String, Optional recursiveSearch As Boolean = False)
	If controlName = [String].Empty Then
		Throw New ArgumentNullException("controlName")
	End If
	If eventName = [String].Empty Then
		Throw New ArgumentNullException("eventName")
	End If
	If targetName = [String].Empty Then
		Throw New ArgumentNullException("targetName")
	End If

	Try
		Dim eventMethod = [GetType]().GetMethod(targetName)
		Dim control = Controls.Find(controlName, False).FirstOrDefault()
		If control IsNot Nothing Then
			Dim eventToSubscribe = control.[GetType]().GetEvent(eventName)
			Dim handler = [Delegate].CreateDelegate(eventToSubscribe.EventHandlerType, Me, eventMethod)
			Dim button = Controls.Find(controlName, recursiveSearch).FirstOrDefault()
			eventToSubscribe.AddEventHandler(button, handler)
		End If
			'handle the exception your way
	Catch ex As Exception
	End Try
End Sub

In order to make this snippet work, you need to ensure that the target method is accessible via reflection. If you use .net 3.5 or lower, remove the optional parameter from the method signature.

Was this snippet helpful? Do you know a better way to do this? Feel free to post a comment!

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 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