how to make a cast in c#

//If you want to make your own cast for your struct or class you
//can overload an operator. Note that you can't make a cast 
//if your your target class is in inheritence with yours.

// This is if you want to manually type out (MyType)b. This is recommened
// if your cast can fail.
public static explicit operator MyType(byte[] b)
{
  MyType m = new MyType();
  m = MagicToConvertByteToMytype(b);
  return m;
}

// This is if you want to do it automatically. 
// This is recommened if your cast is defananlty safe.
public static implicit operator byte[](MyType m)
{
  return m.ToBytes();
}

0
0
C. Flynn 140 points

                                    // if we have:
float f = 12.0f;
// and we want to put the value of f into 
int x;
// we can cast f to int like this:
x = (int)f //(int) is the cast

0
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source