Game Development Reference
In-Depth Information
Again, you'll probably also want to eliminate the possibility that a string consists
entirely of spaces, because a string that is not null and features only white space
characters will not, in fact, be of 0 length, even though it usually means there's
nothing to process. You can validate a string for each of these states individually,
but the string class in .NET offers a compound or all-in-one convenience check
for you, specifically the method IsNullOrWhiteSpace . However, this method
was introduced in .NET 4.5, and Mono does not support this version. This means
a manual implementation is required for equivalent behavior, as shown in the
following code sample 6-11:
using UnityEngine;
using System.Collections;
//-------------------------------------------------------------
//Class extension to add Null or White Space functionality
public static class StringExtensions {
public static bool IsNullOrWhitespace(this string s){
return s == null || s.Trim().Length == 0;
}
}
//-------------------------------------------------------------
public class StringOps : MonoBehaviour
{
//Validate string
public bool IsValid(string MyString)
{
//Check for null or white space
if(MyString.IsNullOrWhitespace()) return false;
//Now validate further
return true;
}
}
//-------------------------------------------------------------
String comparison
You'll frequently need to compare two separate strings, typically, for equality to
determine whether two strings are identical. You can do this using the == operator
such as string1 == string2 , but for best performance, use the theString.
Equals method. This method has several versions, all of varying computational
expense. In general, you should prefer any version that contains an argument of type
StringComparison . When the comparison type is explicitly stated, the operation will
perform best, as shown in the following code sample 6-12:
 
Search WWH ::




Custom Search