Helper method to capitalize a string

Here is a method that you a pass a string an it returns it correctly capitalized.
It makes uses of the System.Globalization namespace.
I have found that it is easier to wrap this call in your own method (like in a helper class) instead of typing it all our or remembering to include the Globalization namespace.

public static string Capitalize(string value)
        {
            try
            {
                return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
            }
            catch (Exception ex)
            {
                throw ;
            }
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Advertisements

Convert Generic List to Array

Here is a method to convert a generic list to an Array.

public static T[] ConvertListToArray<T>(List<T> theList)
{
try
{
if (theList == null)
{
return null;
}

T[] theArray = new T[theList.Count];

for (int i = 0; i < theArray.Length; i++)
{
theArray[i] = theList[i];
}

return theArray;
}
catch (Exception ex)
{
throw ;
}
}

Convert an Array to a generic list

Sometimes you have an array, but a generic list would make better sense.
Here is a method to convert from an array to a generic list.

This comes in handy if you you get an array back a web service (since they can’t return a generic list).

public static List<T> ConvertArrayToList<T>(T[] theArray)
{
try
{
if (theArray == null)
{
return null;
}

List<T> theList = new List<T>();

for (int i = 0; i < theArray.Length; i++)
{
theList.Add(theArray[i]);
}

return theList;
}
catch (Exception ex)
{
throw ;
}
}

How to programmatically determine the current method name

If you want to determine the current method in code (C#) here is the line of code you need.

MethodInfo.GetCurrentMethod().Name

This call will return the current method name as a string.  (It is from the namespace System.Reflection).

Why is this helpful?  If you write a generic logging routine and want to log the current method this is a big help.  So you don’t need to modify your log error call (in your catch) with anything not generic (like hard coding your method name).

 

Here is an example of this.

String currentMethodName = MethodInfo.GetCurrentMethod().Name;

 

If this line is in the Page_Load method, it returns “Page_Load”