Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Between Data Types in C#

I have (for example) an object of type A that I want to be able to cast to type B (similar to how you can cast an int to a float)

Data types A and B are my own.

Is it possible to define the rules by which this casting occurs?

Example

int a = 1;
float b = (float)a;
int c = (int)b;
like image 978
Jimbo Avatar asked Apr 28 '10 10:04

Jimbo


People also ask

What is casting of data types?

A data type that can be changed to another data type is castable from the source data type to the target data type. The casting of one data type to another can occur implicitly or explicitly. The cast functions or CAST specification (see CAST specification) can be used to explicitly change a data type.

How many types of type casting are there in C?

In C programming, there are 5 built-in type casting functions. atof(): This function is used for converting the string data type into a float data type.

What is the syntax of type casting?

The explicit type conversion is also known as type casting. Type casting in c is done in the following form: (data_type)expression; where, data_type is any valid c data type, and expression may be constant, variable or expression.

What is casting operator in C?

Cast operator () In C, the result of the cast operation is not an lvalue. In C++, the cast result belongs to one of the following value categories: If type is an lvalue reference type. or an rvalue reference to a function type.


1 Answers

Yes, this is possible using C# operator overloading. There are two versions explicit and implicit.

Here is a full example:

class Program
{
    static void Main(string[] args)
    {
        A a1 = new A(1);
        B b1 = a1;

        B b2 = new B(1.1);
        A a2 = (A)b2;
    }
}

class A
{
    public int Foo;

    public A(int foo)
    {
        this.Foo = foo;
    }

    public static implicit operator B(A a)
    {
        return new B(a.Foo);
    }
}

class B
{
    public double Bar;

    public B(double bar)
    {
        this.Bar = bar;
    }

    public static explicit operator A(B b)
    {
        return new A((int)b.Bar);
    }
}

Type A can be cast implicitly to type B but type B must be cast explicitly to type A.

like image 64
Daniel Renshaw Avatar answered Oct 05 '22 10:10

Daniel Renshaw