Generic Wrapper Class possible? - c#-3.0

On C# 3.0 and .NET 3.5, imagine there's an interface:
public interface INameable
{
string Name {get;}
}
and many immutable classes that implement the interface.
I would like to have a single extension method
public static T Rename<T>(this T obj) where T : INameable
{
...
}
that returns a wrapped instance of the original object with just the name changed and all other property reads and method calls routed to the original object.
How to get a generic wrapper class for this, without implementing it for all INameable implementing types? Do you think that's possible?

No, this isn't possible, unless T is constrained to be an interface or to be a class with all members virtual, and this constraint isn't possible to specify at compile time (though you could write a runtime check if you're happy with that approach).
The reason you cannot do it for arbitrary types is that if you take an object of type T then you must return an object that is assignable to T. If I pass an object that looks as follows...
public sealed class SomeClass : INameable
{
public string Name { get; }
public string Abc { get; }
}
...then there is no way you can create another type that is assignable to SomeClass. Not using Reflection.Emit or any other method, because the type is sealed.
However, if you're happy with the restrictions that I've mentioned then you could use something like the Castle DynamicProxy framework to create a type that proxies the passed in object and intercepts the calls to either forward or re-implement as appropriate.

Well, yes, it's possible, but it involves generating code in memory.
You can look at Reflection.Emit and here.
Note that it will involve a lot of code.
That is, if I assume I understand you correctly.
Here's what I think you're asking for:
SomeNameableObject a1 = new SomeNameableObject("ThisIsTheFirstName");
SomeNameableObject a2 = a1.Rename("ThisIsTheSecondName");
// a1 works, still has the name ThisIsTheFirstName
// a2 works, but everything is routed to a1,
// except for the name, which is ThisIsTheSecondName
Is that correct?

Related

Very confusing Abstract Class, need guidance

I missed a few CS classes, namely the ones going over topics such as polymorphism, inheritence, and abstract classes. I'm not asking you to do my homework but I have no idea where to even start to get further guidance, so giving me a skeleton or something would help me greatly, I'm so confused.
So the problem is to create an employee abstract class with two subclasses, permanentEmployee and TempEmployee.I must store information such as name,department,and salary in these subclasses and then order them according to how the user wants them ordered. I know I start out like this
public abstract class Employee
{
}
public class TempEmployee extends Employee
{
\\variables such as name, salary, etc, here?
}
public class PermEmployee extends Employee
{
\\here too?
}
but I have no idea how to store variables in there much less access them later for ordering and displaying,. Please guidance.
If all you're looking for is an example of class-level data members in Java, this should help:
public class SomeClass {
private int someInt;
public int getSomeInt() {
return this.someInt;
}
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
Regarding polymorphism, be aware that methods are polymorphic, but values are not. As you place values and methods (getters and setters) in your base class and derived classes, I encourage you to experiment with these concepts thoroughly. Try moving the entire value/getter/setter to the base class, try moving just the value but not the getter/setter, try putting the value in both and the getter/setter in both, etc. See how it behaves.
Make sure that any value/method/etc. that you put in your base class is applicable to all derived classes. If there's ever an exception to that rule, then you would need to move that member out of the base class and into only derived classes where it applies. Note that you can have a complex hierarchy of base classes to accommodate this if needed.
When it comes time to access these members for sorting/display/etc., consuming code would use the getters/setters. For example:
SomeClass myInstance = new SomeClass();
myInstance.setSomeInt(2);
System.out.println(myInstance.getSomeInt());
I am not sure which language you working with, but as it has "extends" I am sure you are not working with c# or CSharp, it can be Java. So I would recommend you to go for TutorialsPoint. This particular article has abstraction described here.
Just to make it easy for you, in Interface and abstraction we always create a structure or the base, it has all the common things defined or declared (Obviously interface has only methods and no variables can be declared inside it).
So as said, in above example, EmployeeId, EmployeeName, EmployeeAddress ...etc should be defined in the base class that is Abstract Base class Employee, But in TempEmployee you can have a criteria such as EmpTermPeriod, EmpContractRenewalDate, EmpExternalPayrollCompanyName (Have made names long and self descriptive) and PermEmployee to have fields like EmpJoiningDate, EmpConfirmationDate, EmpGraduityDate...etc.
I hope it helps.

What is the Guiding Principle of Access Levels meaning in swift

The Guiding Principle of Access Levels of swift is
No entity can be defined in terms of another entity that has a lower (more >restrictive) access level.
For example:
A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used.
A function cannot have a higher access level than its parameter types and return type, because the function could be used in situations where its constituent types are not available to the surrounding code.
could any body show me a code example about
A public variable cannot be defined as having an internal or private type, because the type might not be available everywhere that the public variable is used.
and
A function cannot have a higher access level than its parameter types and return type, because the function could be used in situations where its constituent types are not available to the surrounding code.
I don't know the clearly meaning of the principle of access level
Accessibility levels are, in increasing order:
private - only this file/class
internal - only this module
public - anybody
You can't use
private class Foo {
}
public var myFoo:Foo
because myFoo is visible outside the module but class Foo isn't, therefore anybody using myFoo wouldn't know what to do with it, how big it was, etc. If you change myFoo to private, then it's all good because anybody that has access to myFoo also has access to class Foo.
Likewise, you can't use:
private class Foo {
}
public func getMyFoo() -> Foo {...}
for the same reasons, the caller of getMyFoo doesn't (can't) know what Foo is, so has no way to properly deal with it.
Essentially if a type is private (or not public) then there can't be any external visibility of objects of that type.
Here are some simple examples:
internal protocol InternalProtocol { }
class MyClass {
// V~~~ This won't work, because InternalProtocol is internal, but the variable is public
public let myInternalProtocolVariable: InternalProtocol
// V~~~ This won't work because InternalProtocol is internal, but the function is public
public func publicFunc(ip: InternalProtocol) -> InternalProtocol {
return ip
}
}
The idea is that the caller of the function, or the object accessing the variable has to have access to the types that are used in the function or the variable.
If the user doesn't have access to InternalProtocol - i.e., they can't "see" it - then they shouldn't be able to "see" any variables or functions that use that type either.

Interface Injection chapter in DI

I just start learning what is Dependency Injection and InversionOfControll is. But I cant get one thing. The interface injection is onle when I define some interface where describe method what need to be realized. And that method gets instance of some class as parameter, and then In class what implements interface just describe body of this method ?
An interface is only a contract that defines what public members a class should implement. It does not control the actual implementation - you need a concrete class to do that.
// This is only a contract that defines what members
// all concrete types must implement.
public interface ISomeType
{
void DoSomething();
}
// This class implements the interface. Therefore, it must
// have all of the methods the contract specifies. In some
// languages, this can be done implicitly just by adding the
// member, but it usually must be public.
public class SomeType : ISomeType
{
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
When you make a class implement an interface it implicitly means that instances of the class can be cast to the interface type.
ISomeType x = new SomeType();
Dependency Injection takes advantage of this behavior. You typically define both the interface type and the concrete implementation together in a mapping.
container.For<ISomeType>().Use<SomeType>();
Then when a service is declared to take ISomeType as a constructor argument, the map is used to determine which concrete type to create an instance of.
public class SomeService : ISomeService
{
private readonly ISomeType someType;
public SomeService(ISomeType someType)
{
if (someType == null) throw new ArgumentNullException("someType");
this.someType = someType;
}
}
The recommended way is to allow the DI container to do this implicitly when your entire object graph is composed (in the Composition Root), but it is possible also to do it explicitly (and it makes a better example):
ISomeService = container.GetInstance<ISomeService>();
Assuming that the container was configured to map ISomeService to SomeService (like I showed before with ISomeType), this one line of code will create an instance of SomeService and automatically inject an instance of SomeType into its constructor.
It is difficult to see the point in a simple example, though. Dependency Injection is meant for complex applications with many types. It simplifies things when the application is complex, but when the application is simple it has a tendency to make things more complex.

How to Implement an Interface that Requires Duplicate Member Names?

I often have to implement some interfaces such as IEnumerable<T> in my code.
Each time, when implementing automatically, I encounter the following:
public IEnumerator<T> GetEnumerator() {
// Code here...
}
public IEnumerator GetEnumerator1() {
// Code here...
}
Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs.
When doing so, I manage to set the GetEnumerator1() accessor to private. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException within the method's body.
However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so.
What is the best approach while implementing an interface such as IEnumerable<T> that requires the implementation of two different methods with the same name?
EDIT #1
Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the GetEnumerator1(). Here's the code:
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
// Code here...
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator
// Code here...
End Function
Both GetEnumerator() methods are explicitly implemented, and the compile will refuse them to have the same name. Why?
You can use explicit interface implementation:
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
...
}
In Visual Basic, all interface implementations are explicit.
Interface mappings are defined by the Implements statement so you can name your interface implementation methods whatever you want. (Unlike C#, where the compiler infers which methods implement interfaces by matching their names and signatures.)
Changing the method name and visibility (as appropriate) is standard practice in VB. See Implementing Interfaces in VB.NET for a good overview.
You should be able to use Explicit Interface Implementations to create the two methods that have the same signature. Depending on what you are enumerating, I would just pass these calls through to an internal IEnumerable<T> such as a List or array.
Implementing the non-generic interface explicitly allows both methods to have the same name, and allows the non-generic version to be implemented in terms of the generic one. Along the lines of:
public class TestEnumerable : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
// Type-safe implementation here.
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

What is the base of all interfaces in .net, just like the base for all classes is the object

I would like to pass an interface to a method signature which takes Object as its parameter, so I wonder about this question
public Stream GetViewStream(string viewName, object model, ControllerContext context)
instead of object I shall like to pass an interface Imodel, without modifying the signature. Is there a base class for interfaces?
Also in the new mvc2 is there a way to avoid controllercontext altogether?
I'd only answer the first question - Why there's no common base interface for all interfaces ?
First of all, there's no common pre-defined base interface for all interfaces, unlike the System.Object case. Explaining this can get very interesting.
Let us assume, you could have a common interface for all interfaces in the system. That means, all interfaces will need to force their implementations to provide implementation-details for that common base interface. In general, interface are used to give specific special behaviors to their concrete implementation classes. Obviously you only want to define an interface when you only know what to do and don't know HOW to do that. So, if you let there be a common base interface for all interface and force the implementations to expect them to provide details of how to do it - why would you want to do it ? What common task each class should do that varies from one another ?
Lets look at the other side of the coin, why we have System.object as base class of any .Net type - It is simple it gives you some methods that have COMMON implementation for any .Net type and for those methods that it might vary from type-to-type they have made it virtual ex: .ToString()
There's possibly no assumption of any
system-wide interface method which is
virtual/abstract to all its
implementations.
One common practice of using Interface is say, defining a particular behavior to any type. Like I'd have an interface IFlyable which will give Fly() to all types that implement IFlyable. This way I can play with any Flyable object regardless of its inheritance hierarchy coming into picture. I can write a method like this..
public void FlyTheObject(IFlyable flyingObject)
{
flyginObject.Fly();
}
It does not demand anything from the object but the implementation of the Fly() method.
EDIT
Additionally, All interfaces will resolve to Object because interfaces cannot be instantiated. The object is always of a concrete class that can be instantiated. This class may or may not implement your interface but as we know, any .Net type is ultimately based to System.Object, so you will be able to take the instance into an object type regardless of the fact if it implements a particular interface or not.
No, there is no base class for interfaces. Nor there is base interface for interfaces.
As for your second question (and partly first one) - what are actually you trying to do?
There is no base class for interfaces, but you can pass any interface variable e.g:
private IEnumerable<int> myInterfaceVariable = new List<int>();
to your method because by definition anything that is stored in that variable must be an instance of a class that inherits from the interface - therefore it must be an object.
The following compiles fine:
public class InterfaceAsObject
{
private IEnumerable<int> myInterfaceVariable = new List<int>();
private void CallDoSomething()
{
DoSomething(myInterfaceVariable);
}
private void DoSomething(object input)
{
}
}
Re 1, there is no base interface, but if I understand you correctly, you can achieve what I think you want by just passing your object that implements IModel via the model parameter and cast (and check!) the parameter to IModel. I use 'as' and check for null.
If you don't need total flexibility, a better way of doing this is to define the interface that the model parameter must support. If the specific objects support derived interfaces (e.g. IDerivedModel : IModel) this will work too.
Look up a text-book on polymorphism.