Posts

Showing posts with the label C#

Get C# Enum Description from Name And Value

enum with Description attributes like this: public enum MyEnum { Transaction = 1 , [ Description ( "Transaction Detail" )] TransactionDetail = 2 , [ Description ( "Transaction Reference Number" )] TransactionRefno = 3 } I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects: public static string DescriptionAttr < T >( this T source ) { FieldInfo fi = source . GetType (). GetField ( source . ToString ()); DescriptionAttribute [] attributes = ( DescriptionAttribute []) fi . GetCustomAttributes ( typeof ( DescriptionAttribute ), false ); if ( attributes != null && attributes . Length > 0 ) return attributes [ 0 ]. Description ; else return source . ToString (); } Using an enum like in the original post, or any other class whose property is decorated with the Description attribute,

Generate Random Number And Random String In C#

Image
Generate Random Number And Random String In C# The Random class of .NET class library provides functionality to generate random numbers in C#. The Random class constructors have two overloaded forms. It takes either no value or it takes a seed value. Random number generator in C# The following code returns a  random number  between the min and the max range. /  Generate  a  random number  between two  numbers . public int  RandomNumber (int min, int max) { Random random  = new  Random (); return  random .Next(min, max); } The Random class provides Random.Next() , Random.NextBytes() , and Random.NextDouble() methods. The Random.Next() method returns a random number, Random.NextBytes() returns an array of bytes filled with random numbers, and Random.NextDouble() returns a random number between 0.0 and 1.0. The Random.Next() method has three overloaded forms and allows you to set the minimum and maximum range of the random number. The foll