How to define a casting operator in a superclass in C # 3.5?

I have a container class for adding some properties to standard data types such as int, string, etc. This container class encapsulates an object of this (standard type) object. Other classes then use a subclass of the container class to get / set the added properties. Now I want subclasses to be able to implicitly enter between its encapsulated objects and itself, without having additional code in it.

Here is a simplified example of my classes:

// Container class that encapsulates strings and adds property ToBeChecked // and should define the cast operators for sub classes, too. internal class StringContainer { protected string _str; public bool ToBeChecked { get; set; } public static implicit operator StringContainer(string str) { return new StringContainer { _str = str }; } public static implicit operator string(StringContainer container) { return (container != null) ? container._str : null; } } // An example of many sub classes. Its code should be as short as possible. internal class SubClass : StringContainer { // I want to avoid following cast operator definition // public static implicit operator SubClass(string obj) // { // return new SubClass() { _str = obj }; // } } // Short code to demosntrate the usings of the implicit casts. internal class MainClass { private static void Main(string[] args) { SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass' string testString = subClass; // No error } } 

My real container class has two types of parameters: one for the type of encapsulated object (string, int, ...) and the second for the type of subclass (e.g. SubClass).

How can i make code

 SubClass subClass = "test string"; // ERROR: Cannot convert source type 'string' to 'SubClass' 

is executed by minimal code in subclasses?

+4
source share
1 answer

I don’t think there is a way to define a conversion operator in a base class.

The base class knows nothing about the subclass, so there is not enough information to create it. For example, what if your SubClass type SubClass had a constructor that requires some arguments? The base class does not know about the subclass, so it cannot create it in any way.

Perhaps you can use a different parameterization method of type StringContainer . For example, instead of using implementation inheritance (subclasses), you could pass some functions (delegates of type Func<...> ) to the StringContainer class. That way, the user can parameterize the class, and your implicit conversion will still work.

+1
source

All Articles