Implicit and Explicit Operators in C#

written by Ryan Olshan on Thursday, May 24 2007

For a side project I'm working on, explicit operators have come in handy in the data layer. With explicit operators, you can convert from one class to another using a user-defined conversion operator. For example:

    public class MyClass

    {

        private int _id;

        private string _description;

 

        public int ID

        {

            get { return _id; }

            set { _id = value; }

        }

 

        public string Description

        {

            get { return _description; }

            set { _description = value; }

        }

 

        public static MyClass GetMyClass(int id)

        {

            return (MyClass)AnotherClass.GetRows(id);

        }

 

        public static explicit operator MyClass(DataTable dataTable)

        {

            MyClass myClass = new MyClass();

            myClass.ID = Convert.ToInt32(dataTable.Rows[0]["ID"]);

            myClass.Description = Convert.ToString(dataTable.Rows[0]["Description"]);

            return myClass;

        }

    }

 

    public class AnotherClass

    {

        public static DataTable GetRows(int id)

        {

            DataTable dataTable = new DataTable();

            //...

            return dataTable;

        }

    }

With implicit operators, you can implicitly convert from one class to another using a user-defined operator without casting. For example:

    public class MyClass

    {

        private int _value;

 

        public int Value

        {

            get { return _value; }

            set { _value = value; }

        }

 

        public MyClass()

        {

        }

 

        public MyClass(int value)

        {

            _value = value;

        }

 

        public static void SomeMethod()

        {

            MyClass myClass = new MyClass(2);

            int id = myClass;

        }

 

        public static implicit operator int(MyClass myClass)

        {

            return myClass.Value;

        }

    }

Pretty cool, huh?

Kick this post on .NET Kicks

Similar Posts

  1. Nullable Types
  2. C# GridView Sorting/Paging w/o a DataSourceControl DataSource
  3. VB.NET GridView Sorting/Paging w/o a DataSourceControl DataSource

Post a comment