Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# creating an implicit conversion for generic class?

Tags:

c#

generics

I have a generics class that I used to write data to IsolatedStorage.

I can use an static implicit operator T() to convert from my Generic class to the Generic Parameter T

e.g.

MyClass<double> foo = new MyClass(187.0);

double t = foo;

My question is, how can I do the reverse?

MyClass<double> foo = new MyClass(187.0);
double t = 0.2d;
foo = t;

The implicit operator has to be static, so I'm not sure how I can pass in the instance of my class?

like image 339
Alan Avatar asked Aug 04 '11 18:08

Alan


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

This class shows conversion between T and MyClass, both ways.

class MyClass<T>
{
  public MyClass(T val)
  {
     Value = val;
  }

  public T Value { get; set; }

  public static implicit operator MyClass<T>(T someValue)
  {
     return new MyClass<T>(someValue);
  }

  public static implicit operator T(MyClass<T> myClassInstance)
  {
     return myClassInstance.Value;
  }
}
like image 113
Anders Forsgren Avatar answered Sep 22 '22 21:09

Anders Forsgren