Search This Blog

Friday, March 28, 2014

Null keyword C#

C# > Keywords > Null

Null represent reference that does not refer to any object.
  • default value of reference type variables
  • ordinary value types cannot be null

Example

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public class TestClass
    {
        public void TestMethod() { }
    }

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

        private void Form1_Load(object sender, EventArgs e)
        {
           
            TestClass tc=null;

            tc = new TestClass();
            tc.TestMethod();   // You can call TestMethod method.

            tc = null; // set tc to null => the object is no longer accessible and can now be garbage collected
           
            string s1 = null;

            //int k = null; // Error Cannot convert null to 'int' because it is a non-nullable value type  

            int? k = null; // use a nullable value type instead OK

        }
    }
}