Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a hard time to figure out, how I can implement seemingly easy patterns with the strict typing system that C#'s generic system is restricted to. Coming from a mostly Java background, I am used to wildcards for generic types. Since C# does not allow such things I need your help to figure out the most elegant way to implement the following (my implementation is for a Unity3D project but that's really not important I think):
I have Content Providers that can provide various types of content (s.a. objects of the type "Texture", "String",...)
Therefore I created an abstract generic class and an interface such that my architecture look like this
Furthermore I have Content Receivers that are able to handle the content of a certain type and a managing class with a set of such Content Receivers. I want the logic for what receiver has to deal with the content of a given provider in a style something like this:
public void accept(IUIContentProvider provider){
//1. Check if a receiver for the generic type of the provider exists
//2. Ignore the call if no such receiver exists, otherwise pass the provider to this class and
//let it deal with it in some specific manner.
}
But due to the strong type system of C# it seems to be impossible to do anything elegant using Polymorphism. I also can not explicitly convert the IUIContentProvider apparently. I can not even use an abstract base method like:
public abstract object provideContent()
and to override it with e.g.:
public override Texture provideContent(){...}
At this point I start to wonder if it is even wise to use generics for this purpose in C#...
You said in your abstract/generic class UIContentProvider<T> you wanted to have such method :
public abstract object ProvideContent();
And you want to be able to have this override in your concrete implementation TextProvider :
public override string ProvideContent(){...};
But I think you miss the point of the generic in your abstract class... What is the point of having a type parameter T if you don't use it?
Isn't it what you want ?
public interface IUIContentProvider<T>
{
T ProvideContent();
}
public abstract class UIContentProvider<T> : IUIContentProvider<T>
{
public abstract T ProvideContent();
}
public class TextProvider : UIContentProvider<string>
{
public override string ProvideContent()
{
return "";
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I got a C# class which is making some actions based on data it receives which is held in other classes:
public Class ActionClass
{
public void DoStuff(List<MyItemsClass> data) { ... }
}
It started as a single class with a single items class, but then I needed to add another action class which does its stuff in a different way and receives different items.
Now I got an abstract class for the action part which enforces its derived class to implement how they do their stuff. It left me with a dilemma about the items class.. I want to have a single signature in the abstract class which receives the needed items class:
public abstract DoStuff(List<MySuperItemsClass> data);
So I created a common ancestor also to the 2 different items classes. However, since they have nothing in common, I got an empty class which now serves only for the purpose of being able to pass that super class, while dynamically instantiating the correct derived classes.
Is it a good practice to have an empty class for the purpose of creating a type? Is there another more common way of achieving what I need without the use of an empty class?
Use generic interface instead of abstract class. Class can implement multiple interfaces.
interface IActionClass<T>
{
void DoStuff(T data);
}
class MyClass : IActionClass<List<MySuperItemsClass>>, IActionClass<int>
{
public void DoStuff(List<MySuperItemsClass> data) { }
public void DoStuff(int data) { }
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
It seemed like this was possible, but I can't find a reference on how to accomplish it, though I've seen a few things that are closely related. I have a particular type of class that requires a public or private default ctor. The reason is stylistic; it is a domain aggregate and the only case where a default ctor should be used is during event store replay. There are obvious ways to work around this, but I'm trying to lock this particular type down. At any rate, what I'm hoping to do is create an attribute that can be applied at the class level that would enforce the existence of a default ctor. If one isn't found, it won't compile... or at the very least, give it the big nasty blue underline like [Obsolete()] does. I figured this was potentially doable with Roslyn. Any direction would help. The solution would ideally travel with the project rather than being something that needs to be installed on visual studio.
Just a simple idea, for a public default constructor you could make use of the where T : new() constraint - even though attributes cannot be generic you can supply typeof(HasDefaultConstructor<MyClass>) as an argument to an attribute:
public static class HasDefaultConstructor<T> where T : new() { }
public class CheckAttribute : Attribute
{
public CheckAttribute(Type type) { }
}
[Check(typeof(HasDefaultConstructor<MyClass>))]
public class MyClass
{
public MyClass() { }
}
But it feels a bit hacky having to supply the type you're applying the attribute to, and doesn't work for the non-public constructors, but it does fail at compile-time without needing any addons.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having some troubles making an interface for my class. I tried with a simple public void and that worked. But i cannot get it to work with the public static voids in the code below. I think it has something to do with the enum as a parameter in the method. But How do i fix this?
This is the class:
And this is my interface:
Interfaces are contracts. They specify the method signatures for all methods within the contract.
In your interface, you have:
void FFT(/*stuff*/)
Yet, in your implementation, you have defined
static void FFT(/*stuff*/)
Now, why can't we use static? From Joel Spoelsky
Because an interface is a "contract" or an agreement between the consumer (caller) and the provider (callee). An interface describes what and how the calle will provide functionality. There is no need for static members provided by a third party. Static members cannot be overridden by a provider so they do not belong in an interface.
Interface is a contract between caller and callee. Static member belong to class not to the object, so its no point of making method static.
To explain why this really doesn't make sense, the reason to make an interface is so you can pass an object of your class as a reference to the interface type, so the consumer doesn't need to know which underlying type the object is. For example, you might pass an IEnumerable<Foo> to a method that doesn't need to know or care if this is an array or a list or a hashset, etc., it just wants a sequence of Foos.
Static methods are not associated with an instance, so there is no object to reference. There isn't the concept in C# of a static interface which could be used to reference a class rather than an object.
If you had other classes that you wanted to use interchangeably, you could get rid of the static and make these singletons.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Are there design guidelines for the use of interfaces in the scenario below?
I could declare IDescription in DerivedClass or in the interface ISomeInterface or both. 3 choices, what guidelines would help me decide which is best.
public interface IDescription
{
String Description { get; }
}
public interface ISomeInterface
{
String Name { get; }
String Description { get; }
}
public class DerivedClass : Base, ISomeInterface, IDescription
{
public String Description { get; private set; }
}
It depends on the concrete interfaces and their logical relations. There is no universal solution for every case. 2 options you mentioned will be right at some cirtumstances:
If interfaces are not related (for example IDisposable and IEnumerable), then it's better that class implement two unrelated interfaces.
If interfaces are related. For example IClientAPI and IAdminAPI, then admin interface may derive from client's interface, because administrator can do everything normal user can, plus some additional operations.
The case when interfaces derived and at the same time class implements both parent and children interface is rare if at all possible in well-written code. You can always avoid it. I don't see any problems if you specify interface second time for class itself. At the same time there is no profit as well. So better don't do it.
Important note: Don't build inheritance hierarchy based on just matching property names - they can be same by coincidence. Always think if this is coincidence or fixed relation before creating base class or interface. Otherwise you'll end up with tons of interfaces like IDescription, IName, IID, etc that doesn't mean anything and only complicates the code.
If the description property is meant to represent the same semantic object in both cases, I would have ISomeInterface implement IDescription for clarity. If they are not necessarily the same thing in your design, then no.
Design guidelines basically depend on the requirement in this case. If you declare the Description in ISomewhere, then you will be forced to implement its other properties(which in this case is Name) even in the classes, which do not need the Name property.
On the other hand, if the Name and Description properties are required by all the classes where you will use ISomewhere, then it will be better to use it in single place ISomeWhere.
To get more precise answer, you need to analyze the where these interfaces will be used.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
public class MyTokenStore: ITokenStore
{
public IToken CreateRequestToken(IOAuthContext context)
{
...some code here...
}
public IToken CreateAccessToken(IOAuthContext context)
{
...some code here...
}
}
Which one of below is better ?
Option1 - ITokenStore x = new MyTokenStore(); OR
Option2 - MyTokenStore x = new MyTokenStore()
What are the advanatges of both ?
Can I restrict user from using Option 2 ?
Users decide for themselves which version they use. The advantage of option 1 is that the user can really instantiate any class that implements the interface. Say you have a helper class that contains a method
DoSomethingVeryUseful(ITokenStore store)
then again that method becomes more useful because it can be called with any object that implements said interface.
The advantage of using option 2 is that your class may contain methods that are not part of the interface, and thus those methods can only be used with option 2.
There is no general good response to this, as it fully depends on you concrete case.
ITokenStore x = new MyTokenStore()
mades a "slice" over concrete MyTokenStore instance where not all members are inside ITokenStore, so you missing access to some additional information that may be present in MyTokenStore and is not present in ITokenStore.
On other hand you create an abstraction layer, so gain a flexibility.
The purpose of an interface is to expose functionality that is common to all implementer's and is agnostic of the concrete implementation. If you are trying to pass around multiple concrete objects to a consumer that needs to access an interface method, then cast it as an interface.
However, if you need a specific member on the concrete implementation, use that.
This is not which is better question but more what are you going to do with it ? Somethings to consider
Are you going to have multiple objects implement the interface ?
Are you going to be doing unit testing ?
Are you going to be doing any in Dependency Injection ?
If you can answer yes to at least one of the questions the using a interface is a good idea but if your using a interface just to use a interface you might want to rethink the solution
My suggestion is the below option. Instead creating "new" object, we can go with contructor injection.
public class MyTokenStore{
private readonly ITokenStore;
public MyTokenStore{ITokenStore TokenService)
{
this.TokenStore=TokenService;
}
}