Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I provide custom cast support for my class?

Tags:

c#

casting

How do I provide support for casting my class to other types? For example, if I have my own implementation of managing a byte[], and I want to let people cast my class to a byte[], which will just return the private member, how would I do this?

Is it common practice to let them also cast this to a string, or should I just override ToString() (or both)?

like image 346
esac Avatar asked Sep 10 '09 21:09

esac


People also ask

How do you cast an object to a custom class in Python?

The Cast. _to method, is used to cast your custom object, to the desired class. Use the flow control to handle various cases. In this example, if casting to a str class, it will use the json dumps to convert the object to a json string.

What is implicit keyword in c#?

According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting.

How user-defined conversions work in c#?

Use the operator and implicit or explicit keywords to define an implicit or explicit conversion, respectively. The type that defines a conversion must be either a source type or a target type of that conversion. A conversion between two user-defined types can be defined in either of the two types.


1 Answers

You would need to override the conversion operator, using either implicit or explicit depending on whether you want users to have to cast it or whether you want it to happen automagically. Generally, one direction will always work, that's where you use implicit, and the other direction can sometimes fail, that's where you use explicit.

The syntax is like this:

public static implicit operator dbInt64(Byte x) {  return new dbInt64(x); } 

or

public static explicit operator Int64(dbInt64 x) {     if (!x.defined) throw new DataValueNullException();     return x.iVal; } 

For your example, say from your custom Type (MyType --> byte[] will always work):

public static implicit operator byte[] (MyType x) {     byte[] ba = // put code here to convert x into a byte[]     return ba; } 

or

public static explicit operator MyType(byte[] x) {     if (!CanConvert) throw new DataValueNullException();      // Factory to convert byte[] x into MyType     return MyType.Factory(x); } 
like image 98
Charles Bretana Avatar answered Sep 29 '22 03:09

Charles Bretana