Posts Tagged ‘string’

Trim a String in C#

Anytime a web form accepts user input that is destined for a database, it is (in the majority of the cases) important to trim string inputs. Without knowing, some users may cut and paste strings from one source to your form. For one reason or another, the cut and paste process may carry along unwanted extra spaces or other delimited not easily detected by the human eye. In C#, there are a few ways to handle this:

Let us assume string myString = “  Allied, agents   \r\n\r\n”;

myString.Trim()
This overload of the Trim method will remove whitespaces from both ends of the string. This is by far the most commonly used form of the method used to clean up user inputs. Often times, copy/pasted items contain a trailing space which can cause a lot of issues if not checked for.

String Output of “Allied, agents”.

myString.Trim(‘,’, ‘a’)
This overload of the Trim method will remove only the comma and lowercase letter a from either the beginning or the end of the string. Therefore, in this case, the string output will be exactly the same. Not that the letters specified are case sensitive. Additionally, you are allowed an unlimited number of characters.

String Output =  “  Allied, agents   \r\n\r\n”

TrimEnd(‘,’, ‘a’)
This overload does the exact same thing as Trim(‘,’,'a’), except that the letters are only trimmed from the end of the string.

TrimStart(‘,’, ‘a’)
This overload does the exact same thing as Trim(‘,’,'a’), except that the letters are only trimmed from the beginning of the string.

Convert String to Int in Java

Converting a string variable to an integer variable in Java is easy. There are actually two different approaches, both equally simply. Below is an example of both approaches, with both use the same string variable to output to various integer variables.

String myVariable = “12345″;

Approach 1:
int approach1 = Integer.parseInt(myVariable);

Approach 2:
int approach2 = Integer.valueOf(myVariable);

If you have any opinion on why you use one approach over the other, let the community know!

Call Static Method With a String Name in C#

The situation is as follows. You want to call a method in the currently executing namespace, but you do not know the name of the static method while coding (perhaps the method name is dynamic and saved in a database or text file). How do you dynamically call the static method with just a string name that is only available at runtime? All it takes is FIVE lines of code to accomplish this with the System.Reflection namespace!

Assume the following situation that is depicted in the full example at the bottom of this tutorial:

  • Namespace is MyNamespace
  • Class name is LateBinding
  • Three public static Method (Method1, Method2, Method3) that require zero parameters

STEP ONE – To state the current Assembly: Since the method we want to call is contained within the same codebehind file, it is in what is called the Executing Assembly.

Assembly assemblyInstance = Assembly.GetExecutingAssembly();

STEP TWO – To state the Type: To state the type, we need the Namespace and the Class name. In our example, the namespace is called MyNamespace and the Class is called LateBinding. That leads to the below snippet:

Type thisClass = assemblyInstance.GetType("MyNamespace.LateBinding", false, true);
  1. The first argument is the conbination of the namespace and class name as a string.
  2. The second argument is a boolean variable where true will throw an exception of the first argument is false. If the variable is set to false, it will return null.
  3. The third argument is another boolean variable will true ignores the case of the first argument and false make the first argument case sensitive.

STEP THREE – To state the Method: From the Type we obtained from the previous step, we will store information regarding our method in a MethodInfo object. In this proof of concept example, we will call Method1. At this point, we don’t care about the number of parameters.

MethodInfo m = thisClass.GetMethod("Method1");

STEP FOUR – To call the Method: Now that we have a MethodInfo object, we can call the method via Invoke. Invoke has several different overloads, but in this example, we will use the most simple one with two arguments. It returns an object which we’ll call result. The result stores the return value of the method we are trying to call. 

object result = m.Invoke(null, null);

  1. This first parameter is looking for an object, but because our methods are all static, we can safely leave this argument as null.
  2. The second parameter is an object array of arguments. Since our methods all take zero parameters, this is also null. If you’re method requires a string, you would need to add the string input to the object array.

STEP FIVE – To get the result: Now we know the output of our method is a string, so we’ll convert the result (which is of type Object) to a string.

string s = result.ToString();

We have now called the method via a string. This entire process is called Late Binding and can be used to extend your applications in several ways. One method as stated in the early portion of this tutorial is trying to call a method that has been stored as a name in the database.

Finally, as promised, below is the codebehind with this example:

using System;
using System.Reflection;

namespace MyNamespace
{
    public partial class LateBinding : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Assembly assemblyInstance = Assembly.GetExecutingAssembly();
            Type thisClass = assemblyInstance.GetType("MyNamespace.LateBinding", false, true);
            MethodInfo m = thisClass.GetMethod("Method1");
            object result = m.Invoke(null, null);
            string s = result.ToString();
        }

        public static string Method1()
        {
            return "Called Method 1";
        }

        public static string Method2()
        {
            return "Called Method 2";
        }

        public static string Method3()
        {
            return "Called Method 3";
        }
    }
}