trim in C# code example

Example 1: c# remove spaces from string

string str = "This is a test";
str = str.Replace(" ", String.Empty);
// Output: Thisisatest

Example 2: c# shorten an method

//Full defenition
bool IsEven(int num)
{
  return num % 2 == 0;
}

//Can be rewritten as:
bool isEven(int num) => num % 2 == 0;

//This can only work with one expression methods

Example 3: c# trim string

string hello = " hello world ";
hello.Trim();

Example 4: trim all string properties c#

//Credit [thrawnis] 
//https://stackoverflow.com/users/1886971/thrawnis 
//https://stackoverflow.com/questions/7726714/trim-all-string-properties
/// <summary>Trim all String properties of the given object</summary>
public static TSelf TrimStringProperties<TSelf>(this TSelf l_Data)
{
  var stringProperties = l_Data.GetType().GetProperties()
    .Where(p => p.PropertyType == typeof(string) && p.CanWrite);

  foreach (var stringProperty in stringProperties)
  {
    string currentValue = (string)stringProperty.GetValue(l_Data, null);
    if (currentValue != null)
      stringProperty.SetValue(l_Data, currentValue.Trim(), null);
  }
  return l_Data;
}
// Test 
// var l_Model = new { RespCode = " 000", RespDesp = "Success! " };
// l_Model = l_Model.TrimStringProperties();
//