Operators in .NET

stovellp

Newcomer
Joined
Mar 25, 2004
Messages
10
Ok this is an easy one.

How do I create a custom assignment operator for my own classes in C#? The types to be assigned to my class are DataReader classes (for SQL and Access) so my class may act as a wrapper for them.

Something like
Code:
class Myclass
{
  operator = (accessdatareader adr)
  {
    mydatareader = adr;
  }
}
 
Yep. I want to be able to do:

MyResultType result = sqlDataReader;

or

result = oledbDataReader;

or result = myresulttype;
 
Because I have a wrapper to make it easier to use the Data Adapters, and I also want to extend it into XML, my own config files, MySQL and other data sources, so if I used IDataAdapter I would be more limited.
 
Lol, currently I'm just using functions such as AssignMSSQL(sqlDataAdapter);, I'll just keep it like that.

Is there a reason why the C# creators chose not to allow assignment overloading? I absolutely love C#, it kicked C++ off my favorite language shelf after only a month of using it, so I'm sure they have a valid reason for doing this :)
 
I don't know why they can't but...
For your problem... maybe you could use a property to get the result ?
No ? Don't have to overload the assignement operator and got the job done.
 
Last edited:
You can overload assignment though it's syntax isn't quite the same - you don't overload the "=" operator.

Here's a sample for how to do it:
C#:
public static implicit operator MyResultType(DataReader op)
{
	return new MyResultType(op);
}

This allows assigning a variable of tyep MyResultType to a variable of type DataReader. In my sample, I assume you have a constructor on
MyResultType that takes a DataReader and does something useful with it.

You can replace implicit with explicit if you need to. Check the help on more info.

-Nerseus
 
Back
Top