Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to C# String Null



How to handle null String in C#?

A C# string is an array of characters declared using the string keyword. String objects are immutable, meaning that they cannot be changed once they have been created.

What is C# null?

The null keyword is a particular case for a variable value. The implementation of C# on the CLR represents a null reference by zero bits. When defining a string in a class, don’t initialize it to null. Instead, initialize it to the constant string.Empty

What are Empty Strings?

An empty string is an instance of a System.String object that contains zero characters. You can call methods on empty strings because they are valid System.String objects.

 string s = "";

What are Null Strings?

A null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a NullReferenceException. e.g. given below.

string str = null;
int len  = str.Length;

When running the above code, it will throw NullReferenceException.

How to check null String in c#?

You may use the null keyword to check or assign the value of an object.

string str =null ;
if (str == null)
{
  MessageBox.Show("String is null");
}

In the above code we created a string Object and assigned null and next we check the string is null or not.

IsNullOrEmpty method

string str =null;
if (string.IsNullOrEmpty(str))
{
  MessageBox.Show("String is empty or null");
}

IsNullOrEmpty is a convenience method that enables you to simultaneously test whether a String is null or its value is Empty.

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			string str =null;

			if (str == null)
			{
				MessageBox.Show("String is null");
			}
			else
			{
				MessageBox.Show("String is not null");
			}

			str = "test";

			if (string.IsNullOrEmpty(str))
			{
				MessageBox.Show("String is empty or null");
			}
			else
			{
				MessageBox.Show("String is not empty or null");
			}

		}
	}
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More