Force implementation of default constructor [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interface defining a constructor signature?
I have a mixed hierarchy of classes and interfaces.
For using serialisation I need a default constructor present in
each class. I would really aprreciate if the compiler could tell
me that a default constructor is missing somewhere in the hierarchy.
(seeing the problem at compile time, not in the later tests)
What I would like to have could be some markup or attribute,
but I could not find anything.
Something like:
[ForceDefaultConstructor]
interface IVeryQuickSerializable
{
Serialize();
Deserialize();
}
would be great!
But anything like that is very appreciated.
There is a limitation: I cannot change the Serialisation.
Making it generic would solve the problem, but I do not have
the source. Writing a wrapper might do the job, but it will
have a loophole for objects deriving from the toplevel Serialisation
interface (which may not be altered).

You can't do that in an interface or attribute.
Two thoughts:
integration test: use reflection to find all relevant classes, and check them in a test
expose your serialization code in a generic API that uses the T : new() clause, i.e.
void Serialize<T>(T obj, ...) where T : IVeryQuickSerializable, new()

There most probably are better solutions, but you could write an application that uses reflection to inspect the assembly during the post-build event.

Related

Changing type using the "string" name [duplicate]

I have an existing base type and I would like to cast it to a derived type base upon the name of the type as a string, so something like this:
public void DoStuffInDerivedType(string derivedName) {
(base as Type.GetType(derivedName)).DoThisThing();
}
I'm pretty sure this can't be done but would be good to know for sure. Thanks
EDIT: I understand that I could construct the object using reflection from the type name but I want use an existing object. And also I know this is generally a bad idea. However I wanted to use this for a SpecFlow BDD Feature.
I'll repeat the advice that you probably don't need to do this, but because I have done this operation before:
Convert.ChangeType(ItemToCast, Type.GetType(stringNameOfType)))
Should work for you.
I don't think you need to cast it to the derived type. You should be able to cast it to the base type and use the shared interface (be it a base class or literal Interface) to perform whatever you want done.
If not, consider adding the behavior as an interface requirement so you can do it that way.
Finally: the one possibility where you'd need to do it this way is if you're overriding the casts...in which case I'm almost certain you can't do this without some heavy duty reflection.

foreach for dynamic type C# - dynamic casting? reflection? [duplicate]

This question already has answers here:
How do I use reflection to call a generic method?
(8 answers)
Closed 4 years ago.
I defined various classes like this:
public class Subclass<T> : BaseObject<T>, IObject, IObject<T> { ... }
BaseObject<T> contains all the functionality I need. IObject<T> allows it to be accessed between projects. IObject allows collections to be created: List<IObject>.
BaseObject<T> and IObject<T> have a property T Value;
So I have
public class BaseObject<T> // T is double, int, decimal, long, short, int - in fact anything enumerable
: IObject, IObject<T>
{
[...]
T Value;
[...]
}
The problem I am trying to solve is how to unpack this by type T.
I want to write this function but don't know how in C#:
public void DoProcessing(List<IObject> objectsToBeProcessed)
{
foreach(dynamic singleObject in objectsToBeProcessed)
{
Type unpackedType = [somehow retrieve the type]
BaseObject<unpackedType.GetType()> unpackedObject = [do some kind of conversion of singleObject];
ProcessorClass<unpackedType.GetType()> processor = new ProcessorClass<unpackedType.GetType()>();
processor.Process(unpackedObject);
}
}
I'm finding this quite hard to put into words but I hope that this explanation gets the idea across. Basically I lose the type information when I build the List<IObject> and I need it back later on when I pass it across into another assembly. I want a single central DoProcessing method that can then delegate by type to instances of generics.
How can I get the type information back?
I understand that generics need a type known at compile-time. But this is situation where you only know the type at runtime. The dynamic keyword allows the collection to be iterated, but I haven't found a way to create the bit inside the loop.
Or should I just force everything to a double in BaseObject and then cast it back locally in some way?
I'm a bit lost on this and feel I am missing something obvious. Any ideas welcome.
POSTSCRIPT - CLARIFICATION
The purpose of this is to separate the code-base into two assemblies:
The assembly with BaseObject<T> allows customers and third parties
to write their own business logic which we don't need to see. They
simply subclass the BaseObject into their own code.
The assembly with IObject & IObject<T> contains generic business
logic that we are creating.
We need this separation in so customers can develop their own libraries of code without having to submit it to us. They just send us a list of List<IObject> and we do the rest, calling their subclasses back as necessary.
Surely it is possible!
ALTERNATIVELY
Can anyone suggest a better architectural solution to the two assembly solution I have described i.e. concrete classes in customer code assembly & abstract/interfaces in our framework assembly.
SOLUTION
OK so I've found a simpler solution. Late-binding via Reflection is doable but is hard to implement with my nuanced object model.
Instead, I have replaced the generic type T and implemented a property which is an enum of
public enum ValueType
{
Double,
Boolean,
Integer,
...
}
I then implement overloaded constructors, added this property to the non-generic interface IObject and have removed the generic interface IObject<T> as it's no longer needed.
Returning the value as double or bool is then handled by
public double AsDouble();
public bool AsBoolean();
public int AsInt();
...
in the interface.
It's not elegant or theoretically pure but it means I don't lose type information and can treat instances all the same. I just unpack the ValueType and choose different behaviour programmatically. It also avoids using the dynamic keyword as all values are implemented as double so looping is easy to implement.
On the plus side I have removed a lot of constraints on generics as they were needed up the inheritance hierarchy. It was getting really complicated and the compilation errors were getting too difficult to unravel.
It feels a bit unsatisfactory from a purist perspective, but MongoDB does something similar so that's good enough for me.
I do feel however that C# is "unfinished" in this area and needs a way to upcast or downcast more easily. It's just such an obvious thing to add.
Maybe the Reflection can be wrapped up somehow to make it transparent to the programmer.
Over-engineering, pragmatism and purism. These are the things that weigh on me...
This should be enough to return the type of the object inside your loop:
Type unpackedType = singleObject.GetType();

C# attribute collection [duplicate]

This question already has answers here:
Can you get merged attributes for a class in C#?
(2 answers)
Closed 9 years ago.
I have a certain collection of built-in attributes (like System.Runtime.Serialization.SerializableAttribute) that I want to apply to a certain collection of classes
Is it possible to unite those attributes into one? I don't want to apply all of them to all of my classes explicitly (the attibute collection might change during the development process)
What I want is one attribute, e.g.
public class MyClassAttribute: System.Attribute { ... }
which I could apply easily to my classes
[MyClass]
public class SampleClass { ... }
and that would cause SampleClass to have Serializable attribute and others. Thanks
No, it is not, basically. Actually, [Serializable] is particularly note-worthy because that has different treatment in the compiler - it is not written as an attribute, but as a raw flag (the runtime simply lies if you ask "does it have the [Serializable] attribute" - it checks the flag against the type, and returns what you expect to see, even though that isn't the truth).
I don't think it's possible out of the box, but you could use Mono.Cecil to modify the types in your assembly in a post-build step, removing your collection-attribute and adding the others.
Interesting question. I think a lot of the built-in attributes are sealed so this might not be possible.

Why does the VS Metadata view does not display explicit interface implemented members

The other day i was looking at C# Boolean struct metadata.
Boolean implements the interface IConvertible. But looking at Boolean's members i could not see most of the IConvertible members.
I've done some tests with some colleagues, including creating our own classes, and came to the conclusion that IConvertible must be implemented explicitly for Boolean.
The question is, why are they not visible? I understand it might be a 'by design decision' but i understand that it would add greater value if they were visible to anyone inspecting the metadata.
The tests were done in VS2010 .NET4.0
The reason is that those methods are there just to implement the I-interface and not to augment the class' public interface.
What I mean is that if you have the following:
public class MyClass : IConvertible
{
// implementation
}
You might want MyClass to be convertible, indeed, so you can pass references of it to methods that expect IConvertible:
public void DoSomethingWithConvertible(IConvertible conv)
But you might not want variables of type MyClass to expose the Convert methods. You simply don't want MyClass's public interface to have that method, then you implement the interface explicitly. That's the whole idea of the approach. This means the following is not allowed:
MyClass a = new MyClass();
a.Convert();
However, the following is still be allowed:
MyClass a = new MyClass();
((IConvertible)a).Convert();
The whole idea behind this is that even though we're using the exact same instance, a as MyClass doesn't have the method. A as IConvertible does have the method. Think of it as if you're allowing the instance to have split personality.
Usually I end implementing every interface implicitly. However, there are very specific situations where I'd implementing them explicitly exactly for the reasons outlined above.
BTW, thanks for the great question!
Because explicit interface implementation actually hides the implementation.
The metadata does indeed show the explicitly implemented. Do you mean intellisense and not metadata?
I'd say that's by design and help the developer of say Boolean to restrict the interface to a subset. By restricting what's suggested to use it also becomes visible what's considered abnormal usage. E.g. it's generally not advised to view a Boolean value as a specific numeric value but in certain cases it's handy to be able to do that anyways.
IDictinary<T,K> is another example. It implements IEnumerable<KeyValuePair<T,K>> making it possible to iterate over all the pairs in the collection and ICollation<KeyValuePair<T,K>>. So you can call Add on the dictionary given a KeyValuePair but usually you should use Add(K, key, T Value)
Try inspecting the class with a tool that provides read access to metadata. ILDASM for one and you can indeed find metadata of the explicitly implemented methods.
They are explicitly implemented. You can find all implemented convertables here: http://msdn.microsoft.com/en-us/library/system.boolean.aspx

Can't specify static methods as part of an Interface?

I have a set of objects that I want to conform to an interface, say ISpecialObject.
However a part of my implementation I want to encapsulate the instantiation trigger of these specialobjects within the implementation of each ISpecialObject.
So say for instance I have as list of class types that implement ISpecialObject, I then want to go through each one and call a static method like CanCreate(some data) which tells me whether or not to create an instance of one of these.
However, .net doesn't seem to let me specify this static CanCreate as part of the ISpecialObject interface.
Can anyone suggest a way to get around this, or alternatively a better approach to solving the problem of encapsulation of the instantiation of these objects? I may just be thinking about this all wrong.
Thanks.
Edit: I may have phrased some parts of this poorly. I don't want to provide the implementation in the interface, but rather specify that there will be one, and that it will be static. Essentially I want the objects to be self defining by allowing a higher level object to query when to create them at runtime.
From what I understand, your main issue is the instantiation of a set of objects that conform to the same interface. If that is so, you may want to look at the Factory Design Pattern which is the standard way to encapsulate such logic.
.NET does not allow static method declarations on interfaces. They don't really make sense since interfaces are all about the contract and avoid implementation entirely. Static methods are specifically about implementation. Additionally, interface methods are virtual function calls depending on the type of the instance, whereas static methods are independent of an instance or even a class (they could be put on any concrete type).
If you have many implementations of ISpecialObject, you could use a factory pattern. In order to do this, you would define define an interface called ISpecialObjectFactory alongside ISpecialObject:
class ISpecialObjectFactory
{
ISpecialObject CreateInstance(...);
bool CanCreate(...);
}
Each class that implements ISpecialObject should have a corresponding ISpecialObjectFactory (e.g. UserObject would have also have a UserObjectFactory). This would require a bit more code, but it's a common pattern and I believe it solves your problem.
I dont see the issue. The typename is just a prefix when dealing with static methods. It will make no difference what so ever if the static method lives somewhere else.
That said, look at extension methods, which may do want you really want it to :)
Edit: Another option might be using attributes.
We just discussed something very similiar to this on another thread. Extension methods are definitely a way to solve this problem. They can provide an implementation for an interface, and the methods can be treated as static or used as a method on an instance of an object which is being extended.
It is not exactly a duplicate in the way that you've phrased the question, but it is duplicate in nature so check out the link below.
StackOverflow - subclass-needs-to-implement-interface-property-as-static
Maybe you can use an abstract class as super class for your purpose. So the static methods go in the abstract class and all derived classes have that as well. However, I agree to the the posts above that may be using the factory pattern is a better approach here.

Categories