Use implicit keywords for implicit conversion of custom types, implicit keywords

Source: Internet
Author: User

Use implicit keywords for implicit conversion of custom types, implicit keywords

In C #, the implicit keyword can be used for implicit conversion of custom types. The following is an example.

First define a Point class to indicate a Point:

    public class Point    {        public double X { get; set; }        public double Y { get; set; }    }


Then, define a static method in the Point class for implicit conversion from string to Point type:

    public class Point    {        public double X { get; set; }        public double Y { get; set; }        public static implicit operator Point(string constValue)        {            var result = new Point();            try            {                var arPoint = constValue.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);                result.X = Convert.ToDouble(arPoint[0]);                result.Y = Convert.ToDouble(arPoint[1]);            }            catch            {                result.X = 0;                result.Y = 0;            }            return result;        }    }

The process of use is very simple, just like our implicit conversion:

            Point p = "3,4.5";            Console.WriteLine("X:{0}, Y:{1}", p.X, p.Y);


Note: Try to avoid errors during implicit conversion or handle exceptions. Otherwise, use explicit to change to forced conversion.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.