Why can't interface members be non-public? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Non Public Members for C# Interfaces
Suppose I have
internal interface IInterface
{
int MyProperty { get; set; }
}
public class MyClass : IInterface
{
internal int MyProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
I get this:
does not implement interface member; cannot implement an interface
member because it is not public;
I know what's the fix, but I am wondering why doesn't C# let interface members to be private.
Many times over I wanted my classes to follow a pattern, but needn't expose the members to public, say when I am writing a library. And best of all, the Interface itself is not public :X
Note: I am not asking how to implement private interface members, but I am knowing the design logic that went behind this decision. I couldn't find a suitable duplicate.
Update: More than the original thread, this code sample from the answer in another thread explains it better than most description answers. Or even better, from #JonSkeet this

An interface is used to define a contract, by making the fields/methods private there is really no point in using an interface then. How does the client know how to use the contract?
Unless you really need an abstract class.

The point of interfaces is that they provide a contract that other objects can use to communicate with your object. There would be not point of making the members private because it would not be useful anymore

Related

Using generic types in C# [closed]

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 "";
}
}

What is the difference between an interface with default implementation and abstract class? [duplicate]

This question already has answers here:
Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?
(6 answers)
Closed 3 years ago.
C# 8.0 has introduced a new language feature – default implementations of interface members.
public interface IRobot
{
void Talk(string message)
{
Debug.WriteLine(message);
}
}
The new default interface implementations provides the elements of the traits language. However is is also blurring the line between what is an abstract class and what is an interface.
What is now the benefit of using an abstract class instead of an interface with default implemenation?
Funny enough, but the CLR implements default interfaces as abstract classes. CLR supports multiple inheritance. Here is a good article about this.
In C#, you need default interfaces when you need to implement (in this case actually inherit from) multiple interfaces, because the language doesn't let you inherit from multiple classes.
An abstract class also allows you to have state. State, i.e. fields, are not allowed in interfaces.

Why to use Overriding? [duplicate]

This question already has answers here:
C# virtual keyword
(9 answers)
C# - Keyword usage virtual+override vs. new
(11 answers)
Can you write virtual functions / methods in Java?
(6 answers)
Closed 4 years ago.
In an interview it was asked why do we need to override method of base class.
I tried to answer like when we want to have different implementation in derived class.
But then he said, "Why don't we just create a new method with different name and different implementation instead of overriding base class method?", anyway we are not reusing base class method as implementation will be different then just create a new method instead of overriding.
I got confused what to answer. Could somebody explain.
public class BaseClass
{
virtual void Foo(){}
}
public class DerivedClass: BaseClass
{
override void Foo(){}
}
Generally we implement overriding like above.
What he said is like why do we need concept of overriding we can do like below
public class BaseClass
{
void Foo(){}
}
public class DerivedClass: BaseClass
{
void Foo1(){}
}
His question was looking weird I tried to explain but like its a method of base class we are just redefining it in derived class. In this way our code will be clean as well. But looks like he was not satisfied.
I would check this answer:
Why does this polymorphic C# code print what it does?
then try to grasp the concept of methods in an object basically having pointers to code. When you override implementation in an subclass then that becomes the new code pointed to, whether it's used or cast as a superclass or not.
So the main purpose of overriding is to create classes that inherit from one class but each have their own implementation and then be able to treat or operate on them equally the same as the original superclass. This is the essence of the Liskov Principle or the 'L' in SOLID. What is an example of the Liskov Substitution Principle?

C# interface design guidelines, interfaces implementing interfaces [closed]

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.

Is it possible to define valid C# interface that cannot be implemented? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm thinking about this (meta) question for couple of days already:
Is it possible to define valid C# interface, that cannot be implemented in any way?
Possible variations of this question: Is it possible to define such interface in C# 2.0, 3.0, 4.0, 5.0? Is it possible to define such interface that would not even compile when implemented, or that would compile but throw runtime exception?
Edit: I know such interface will be useless just by definition, but is a nice answer for lectures or testing applicants for a programming job how good they know C#.
Is it possible to define valid C# interface that cannot be implemented?
This trivia question is not a good fit for StackOverflow, but what the heck, it is easily answered. (Wrongly, as it turns out! Read on!)
class C
{
private C() {}
}
interface IFoo<T> where T : C, new()
{
}
IFoo<T> cannot be implemented for any T because there is no type argument that can be substituted for T. C doesn't work because C does not have a public parameterless constructor, and there can be no derived class of C because the default constructor is private. (Well, there could be an accessible derived class of C inside C, but there isn't in this case.)
UPDATE: Commenter "mike z" correctly points out that
class X<T> : IFoo<T> where T : C, new() {}
implements the interface, though of course now there is no way to instantiate X<T>!
Even better, user "GranBurguesa" points out that a derived class of C is permitted to be declared, just so long as it never calls the private constructor; this is only possible if it crashes and dies on instantiation. (Well, to be picky, it would also be permitted for the recursive calls to be optimized down to an infinite loop instead of a crash.)
Both devious workarounds pose a philosophical question: if an interface is implemented by a class no one can instantiate, is it really implemented? Of course GranBurguesa demonstrates that IFoo<D> can be implemented and constructed, so my answer is actually wrong.
There are also cases, such as the one hinted at in SLaks' deleted answer, in which an abuse of the generic mechanism leads to an "infinitary" type. Such types are not legal in the CLR; the C# design team has considered adding similar language to the C# compiler spec but hasn't gotten around to it yet. Use of these types can crash the compiler or the runtime.
For an example of an infinitary type that crashes the compiler, see my article:
To Infinity But Not Beyond
Here's one. Cut n paste this code into Visual Studio and you'll see that this interface cannot be implemented:
interface ΙAmAPerfectlyOrdinaryInterface { }
class C : IAmAPerfectlyOrdinaryInterface { }
As long as we're talking trivia, I think this is a valid implementation of Eric Lippert's attempt:
class Program
{
static void Main(string[] args)
{
D test = new D();
}
}
class C
{
private C() { }
}
interface IFoo<T> where T : C, new() { }
class D : C
{
public D()
: this(5) { }
public D(int x)
: this() { }
}
class Dfoo : IFoo<D> { }
It compiles fine but crashes with a StackOverflowException when you instantiate D.
If you're trying to factor out an old interface you could mark the interface with the ObsoleteAttribute attribute.
Edit: as #Magnus noted in the comments, if you set the Error attribute to true it's usage will cause an error.
If a type is accessible and unsealed, it will be possible for outside code to create instances of that type and there isn't really anything the base type can do about it. No "full trust" or Reflection required.
public class CantDeriveMe
{
private CantDeriveMe()
{
}
public override string ToString()
{
return "My type is " + this.GetType().ToString();
}
}
public class OhYeah : CantDeriveMe
{
static OhYeah CapturedInstance;
~OhYeah()
{
CapturedInstance = this;
}
OhYeah() : this(1/String.Empty.Length)
{
}
OhYeah(int blah) : this()
{
}
public static OhYeah Create()
{
try
{
new OhYeah(4);
}
catch (DivideByZeroException)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
return CapturedInstance;
}
public static void test()
{
OhYeah it;
it = OhYeah.Create();
Console.WriteLine("Result was ({0})", it);
}
}
Note that if code is written only in C#, a base-class destructor might squawk if it notices that the object isn't of a legitimate type, but code written in languages other than C# would allow the override of Finalize to exit without chaining to its parent.
I think it's possible to specify an open generic interface with a combination of struct and class constraints which no combination of types could possibly fulfill, e.g.
public interface evil<T, U>
where T : struct,U
where U : class
I'm not sure whether such an open-generic type would really qualify as an "interface", though, or whether only closed generic types can really qualify as interfaces (or classes, or structs).

Categories

Resources