- Back to Home »
- Cadenas nulas y cadenas vacías
Posted by : Unknown
martes, 17 de junio de 2014
Una cadena vacía es una instancia de un objeto System.String que contiene cero caracteres. Las cadenas vacías se utilizan habitualmente en distintos escenarios de programación para representar un campo de texto en blanco. Puede realizar llamadas a métodos en cadenas vacías porque son objetosSystem.String válidos. Las cadenas vacías se inicializan tal y como se indica a continuación:
string s = String.Empty;
Por el contrario, una cadena nula no hace referencia a una instancia de un objeto System.String y cualquier intento de llamar a un método en una cadena nula provoca una excepción NullReferenceException. Sin embargo, puede utilizar cadenas nulas en operaciones de concatenación y comparación con otras cadenas. Los ejemplos siguientes muestran algunos casos en los que se hace referencia a una cadena nula y no se produce una excepción:
static void Main() { string str = "hello"; string nullStr = null; string emptyStr = String.Empty; string tempStr = str + nullStr; // Output of the following line: hello Console.WriteLine(tempStr); bool b = (emptyStr == nullStr); // Output of the following line: False Console.WriteLine(b); // The following line creates a new empty string. string newStr = emptyStr + nullStr; // Null strings and empty strings behave differently. The following // two lines display 0. Console.WriteLine(emptyStr.Length); Console.WriteLine(newStr.Length); // The following line raises a NullReferenceException. //Console.WriteLine(nullStr.Length); // The null character can be displayed and counted, like other chars. string s1 = "\x0" + "abc"; string s2 = "abc" + "\x0"; // Output of the following line: * abc* Console.WriteLine("*" + s1 + "*"); // Output of the following line: *abc * Console.WriteLine("*" + s2 + "*"); // Output of the following line: 4 Console.WriteLine(s2.Length); }