the following code used to work fine under vs2008:
namespace N2.Engine.Globalization
{
public class DictionaryScope : Scope
{
object previousValue;
public DictionaryScope(IDictionary dictionary, object key, object value)
: base(delegate
{
if (dictionary.Contains(key))
previousValue = dictionary[key];
dictionary[key] = value;
}, delegate
{
if (previousValue == null)
dictionary.Remove(key);
else
dictionary[key] = previousValue;
})
{
}
}
}
but now it reports An object reference is required for the non-static field, method, or property 'N2.Engine.Globalization.DictionaryScope.previousValue'
It seems something changed in the compiler? Any workarounds?
update:
regarding the suggestion to use a virtual method. This probably wouldn work either, as the virtual method would get called from the base constructor, which I believe is also not possible?
Here is the implementation of the Scope (base class):
public class Scope: IDisposable
{
Action end;
public Scope(Action begin, Action end)
{
begin();
this.end = end;
}
public void End()
{
end();
}
#region IDisposable Members
void IDisposable.Dispose()
{
End();
}
#endregion
Update:
§ 7.5.7 This access
A this-access consists of the reserved word this.
this-access:
this
A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor.
This is none of these. The 4.0 compiler looks to be correct. Presumably it isn't happy because this in essence provides access to this at a point when the type isn't initialized. Maybe ;-p
Note that I expect that it isn't really the this.someField that causes this - more that the use of a field causes this to be captured, meaning it wants to hoist the this instance onto a compiler-generated class - as though you had written:
public MyCtor() : base( new SomeType(this).SomeMethod ) {...}
The C# 3.0 compiler spots the above abuse of this.
Reproduced. Investigating. It looks like an issue resolving the implicit this in the constructor chaining.
The most likely workaround would be to use a virtual method instead of a delegate, and simply override it in the derived class.
One workaround would be to pas the instance in as an argument, so the delegate becomes "obj => obj.whatever...", and use theDelegate(this);.
Simpler repro:
public class MyBase {
public MyBase(Action a) { }
}
public class MySub : MyBase {
private string foo;
// with "this.", says invalid use of "this"
// without "this.", says instance required
public MySub() : base(delegate { this.foo = "abc"; }) { }
}
I would need to check the spec, but I'm not sure whether this is valid in this context... so the 4.0 compiler could be correct.
Add:
static object previousValue;
Related
Firstly, sorry for my English. I hope i can explain my problem.
I have class like this
public class CarCommandExecutorBase
{
protected readonly ICarCommand CarCommand;
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
}
Also i have class like this
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
public CarStringCommandExecutor(Car car)
{
// this Constructor gives me an error.
}
public void ExecuteCommand(string commandObject)
{
}
}
Error message:
[![error][1]][1]
What's the reason and how can i fix it? Thanks.
Since the only constructor in CarCommandExecutorBase is defined like this
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
you have to pass an ICarCommand when creating an instance of CarCommandExecutorBase.
You have to provide an ICarCommand through the constructor of CarStringCommandExecutor, because when instantiating a derived type the base constructor(s) also get called.
See this answer for more detailed information about this: https://stackoverflow.com/a/1882778/8450550
You could do something like this to solve this error:
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
...
public CarStringCommandExecutor(Car car, ICarCommand carCommand)
: base(carCommand) // base() points to the constructor of the base class
{
...
}
or maybe this
public class CarStringCommandExecutor : CarCommandExecutorBase, IStringCommand
{
...
public CarStringCommandExecutor(Car car)
: base(null) // passing null but be aware of NullReferenceExceptions
{
...
}
or you add another constructor to CarCommandExecutorBase which expects no arguments:
public class CarCommandExecutorBase
{
protected readonly ICarCommand CarCommand;
public CarCommandExecutorBase(ICarCommand carCommand)
{
CarCommand = carCommand;
}
// mark this constructor as protected, so only deriving types can call it
protected CarCommandExecutorBase()
{
}
}
Which solution works best in your case is up to you.
One of the things that isn't immediately apparent, thanks to "compiler magic", about a C# class is that every class has a constructor
It needs to be this way because it's a rule that object construction happens in a tree; you construct some class Z which inherits from Y which inherits from X which inherits from object, and Z's cosntructor invokes Y's invokes X's invokes object's, then they finish, in order of object, X, Y, Z and you have your nicely constructed thing - every constructor on the way up the tree had its chance to do its init and ready the object for use (the part of it that each constructor was responsible for)
Even classes that don't seem to have constructors, have constructors:
class X {
}
If you don't provide a constructor, C# provides one for you. You never see it in your source code; just imagine that in between reading the file and compiling it, the compiler inserts it for you. It takes no parameters, has no code, and does nothing other than call its base:
class X {
X():base() { } //C# invisibly writes this for you
}
If you provide a constructor but don't write the base... bit, C# puts base() in for you behind the scenes (and it always calls the no-argument base()) but critically it doesn't provide an empty constructor if you provided one already
This means if you have a class like:
class X{
X(string message){
...
}
}
Your class X has a constructor, so C# won't provide the empty one, so now anything that tries to construct your class must provide a string message:
X x = new X("hello");
If you now inherit from X, you might do one of 3 things (with Y):
class Y:X{
}
You don't add a constructor, C# adds one, but it just dumbly calls base(), which doesn't work because there is no constructor in X that takes no args:
class Y:X{
Y():base() { }
}
You add a constructor but leave off the base bit. C# adds it, again just literally as base() - this also doesn't work for the same reason
class Y:X{
Y(int myArg) //c# adds base() in here for you
{
...
}
}
You add a constructor that includes a call to base and because you know your base class only has a constructor with a string arg, you pass one:
class Y:X{
Y(int myArg) : base("hello")
{
...
}
}
So you're in scenario 2, and you either need to:
Add a no-arg constructor to the base class so that c#'s auto-inserted stuff works or,
Add a call to base(...) with a suitable argument, to stop C# from putting a base() in
I've left out access modifiers from code in this answer for clarity of demonstrating the essential point. Whether a constructor is accessible or not can also have a bearing on all this, but I deemed it out of scope
today I saw a snipped that looked really horrible to me, but unfortunetly I cannot simply change it, so I wonder if I can bypass this somehow. I have a class with a constructor that has an output-parameter for success. But that looks really ugly to me. And now when deriving from this class I have to take this param with me- if I want to or not.
class ClassA {
ClassA(out bool success) {...}
}
class B: ClassA {
// call the constructor from ClassA but without the out-param
}
So I´d know if its good practise or if not how I can avoid declaring the out-param from ClassB.
While passing ref or out parameters to a constructor is ugly, there are some types where attempts to create a usable instance will have side-effects, and might fail after some of those side-effects have already occurred. If it is not possible to construct a valid object, the only ways via which the constructor can pass information to the caller are by storing it in a threadstatic field, encapsulating it within the thrown exception, storing or feeding it to a passed-in object or delegate, or writing it to a ref/out parameter. Of those, only the ref/out parameter makes obvious the existence of information with which the client code should be doing something.
The existence of ref or out parameters is often an indication that a constructor should be protected, and that outside code should go through a factory methods which ensure that if an exception is thrown the passed-out object will get used suitably. For a class to reasonably support inheritance, however, it must offer at least one constructor which is visible outside it. Having that constructor use an out or ref parameter may be the least evil way for a class to let a caller know what things will need cleaning up if construction fails.
You can do something like this:
class ClassA
{
protected ClassA(out bool success)
{
success = true;
}
}
class B : ClassA
{
[ThreadStatic]
static bool success; // static to use in base(out success) call
public bool Success
{
get;
private set;
}
public B()
: base(out success)
{
Success = success;
success = false; // reset value
}
}
It's ugly, but at least you get rid of the out parameter if so you want.
Well, the design of that class is broken anyway, so let's break it a bit more (NOTE! I do not recommend this approach!):
void Main()
{
}
public class ClassA
{
public ClassA(out bool success)
{
success = true;
}
}
public class B: ClassA
{
private static bool success;
// call the constructor from ClassA but without the out-param
public B()
: base(out success)
{
}
}
Other than that, the closest you can get is making a factory method:
public class B : ClassA
{
public static B Create()
{
bool success;
var result = new B(out success);
if (success)
return result;
// TODO: Dispose result?
throw new StupidProgrammerException();
}
}
If you really don't care about the value of the out parameter, in newer versions of C# you can declare an out variable inline and you can choose to do nothing with it:
class B : ClassA
{
B() : base(out bool ignore) { }
}
You can go further and use the special discard name _ to let the compiler know you won't use the variable. This way you don't even need to declare its type:
class B : ClassA
{
B() : base(out _) { }
}
In C++ it is done with "using", and in C#?
public class foo
{
public void print(string s) {...}
}
public class bar : foo
{
// shadowing
public void print(object o) {...}
}
How to promote foo.print, so foo.print and bar.print would be at the same "level" for compiler (for bar of course)?
Update 1
Originally I added a paragraph about common confusion between shadowing and overriding, but then I deleted it, because I thought it will be offensive to readers.
Shadowing is like overloading spanned over inheritance tree. Shadowing is NOT overriding.
Update 2
After shadowing foo.print is no longer taken into account when resolving the overloaded method print. Promoting foo.print would get it back into process -- so when I call bar_object.print("hello") the method foo.print would be called.
In your concrete example, bar.print(object) indeed "shadows" the more specific foo.print(string):
new bar().print("i am a string");
This will call the method defined on bar, although the method on foo would have a parameter that matches the type better.
What happens here is the following: The compiler finds a method on bar with the right name ("print"), the right number of parameters (1) and a parameter type to which the passed in parameter is convertable to (string can be converted to object).
Because of this, there is no reason for the compiler to look further up the inheritance chain.
As far as I am aware, there is no construct similar to C++'s using.
If you want to use the method defined on the base class, you basically have three options:
On the caller side: Convert the bar instance to foo:
var bar = new bar();
var foo = (foo)bar;
foo.print("i am a string"); // Will call foo.print(string)
On the calee side: Inside bar.print(object) check the type of the passed parameter:
public void print(object o)
{
var s = o as string;
if(s != null)
base.print(s);
else
{
// Other code.
}
}
This will come the closest to the C++ using: Actually override or hide the original method in the derived class:
public class bar : foo
{
public new void print(string s)
{
base.print(s);
}
public void print(object o)
{
// some code
}
}
In the code below I tried in two ways to access the parent version of methodTwo, but the result was always 2. Is there any way to get the 1 result from a ChildClass instance without modifying these two classes?
class ParentClass
{
public int methodOne()
{
return methodTwo();
}
virtual public int methodTwo()
{
return 1;
}
}
class ChildClass : ParentClass
{
override public int methodTwo()
{
return 2;
}
}
class Program
{
static void Main(string[] args)
{
var a = new ChildClass();
Console.WriteLine("a.methodOne(): " + a.methodOne());
Console.WriteLine("a.methodTwo(): " + a.methodTwo());
Console.WriteLine("((ParentClass)a).methodTwo(): "
+ ((ParentClass)a).methodTwo());
Console.ReadLine();
}
}
Update ChrisW posted this:
From outside the class, I don't know
any easy way; but, perhaps, I don't
know what happens if you try
reflection: use the Type.GetMethod
method to find the MethodInfo
associated with the method in the
ParentClass, and then call
MethodInfo.Invoke
That answer was deleted. I'm wondering if that hack could work, just for curiosity.
Inside of ChildClass.methodTwo(), you can call base.methodTwo().
Outside of the class, calling ((ParentClass)a).methodTwo() will call ChildClass.methodTwo. That's the whole reason why virtual methods exist.
At the IL level, you could probably issue a call rather than a callvirt, and get the job done - but if we limit ourselves to C# ;-p (edit darn! the runtime stops you: VerificationException: "Operation could destabilize the runtime."; remove the virtual and it works fine; too clever by half...)
Inside the ChildClass type, you can use base.methodTwo() - however, this is not possible externally. Nor can you go down more than one level - there is no base.base.Foo() support.
However, if you disable polymorphism using method-hiding, you can get the answer you want, but for bad reasons:
class ChildClass : ParentClass
{
new public int methodTwo() // bad, do not do
{
return 2;
}
}
Now you can get a different answer from the same object depending on whether the variable is defined as a ChildClass or a ParentClass.
As mentioned above, something is bad with your class design if you need to call "base.base" in PRODUCTION code. But it is quite legitimate to use this technique if you are debugging or searching some workarrounds while using external libraries you cannot compile. It is unpleasant that C# does not provide this option directly. Still you may use Kenneth Xu solution with IL generator and Emit. It works.
class A { public virtual string foo() { return "A"; } }
class B : A { public override string foo() { return "B"; } }
// now in class C
class C : B {}
// we can call virtual method "foo" from A using following code
MethodInfo fooA = typeof(A).GetMethod("foo", BindingFlags.Public | BindingFlags.Instance);
DynamicMethod baseBaseFoo = new DynamicMethod(
"foo_A",
typeof(string),
new[] { typeof(A) },
typeof(A));
ILGenerator il = baseBaseFoo.GetILGenerator();
il.Emit(OpCodes.Ldarg, 0);
il.EmitCall(OpCodes.Call, fooA, null);
il.Emit(OpCodes.Ret);
// call foo() from class A, it returns "A"
(string)baseBaseFoo.Invoke(null, new object[] { this });
For reference and a complete sample see
http://kennethxu.blogspot.cz/2009/05/cnet-calling-grandparent-virtual-method.html
Thank you Kenneth Xu!
As Mark Gravell said, no, not externally. But here's another hack I have used. ChildClass can expose methodTwo() from the ParentClass for its own use or for external use. In your case:
class ChildClass : ParentClass {
override public int methodTwo() {
return 2;
}
public int ParentClass_methodTwo() {
return base.methodTwo();
}
}
// Now instead of
Console.WriteLine("ParentClass methodTwo: " + ((ParentClass)a).methodTwo());
// use
Console.WriteLine("ParentClass methodTwo: " + a.ParentClass_methodTwo());
In my case, the child class introduced the concept of a Peer, and I needed its override of methodTwo() to invoke the base version on the peer. By overridding it, however, it hid it... Or did it? This technique came to the rescue.
class ChildClass : ParentClass {
ChildClass peer;
override public int methodTwo() {
return peer.ParentClass_methodTwo();
}
private int ParentClass_methodTwo() {
return base.methodTwo();
}
}
To my knowledge, once a method has been overridden then you can't call the parent method.
public class Parent
{
public string Method()
{
return "parent";
}
}
public class Child:Parent
{
public string Method()
{
return "child";
}
}
Above code successfully overrides parent method yet value of parent method still unchanged.
You can return values from the Both Parent class and Child class using code below -
Child child = new Child();
string result = (((Parent)child).Method()) + child.Method();
But Visual Studio will show you a warning in Compile Time.
I would think that it is not possible unless you make instance of the ParentClass directly.
Thats the very essense of inheritance, polymorphism...
I stumbled upon this looking for help and ended up with my own approach to calling ancestor versions of a method. This is more of a work-around which assumes you can edit the ancestor class:
Put the functionality in question in the ancestor class into a static method, with the necessary parameters. The method in that class can call it so it need not duplicate the functionality, and the child class can call to that functionality if desired via the static method. That way, it can be done even within a method and can cite which specific class it wants to invoke. Also, it can access farther back ancestors than mere parents, which is the limitation of use "base".
Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself.
The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you can for a struct type:
public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
At any point a struct can alter itself by assigning to 'this' like so.
using the this keyword ensures that only variables and methods scoped in the current type are accessed. This can be used when you have a naming conflict between a field/property and a local variable or method parameter.
Typically used in constructors:
private readonly IProvider provider;
public MyClass(IProvider provider)
{
this.provider = provider;
}
In this example we assign the parameter provider to the private field provider.
only correct place for this from syntax point of view, is Extension methods in C# 3.0 when you specify first parameter of method as foo(ftype this, ...). and then can use this extension for any instance of ftype. But is's just syntax and not real this ovveride operation.
if you're asked to assign something to this, there's quite a few examples. One that comes to mind is telling a control who his daddy is:
class frmMain
{
void InitializeComponents()
{
btnOK = new Button();
btnOK.Parent = this;
}
}
I know this question has long been answered and discussion has stopped, but here's a case I didn't see mentioned anywhere on the interwebs and thought it may be useful to share here.
I've used this to maintain immutability of members while still supporting serialization. Consider a struct defined like this:
public struct SampleStruct : IXmlSerializable
{
private readonly int _data;
public int Data { get { return _data; } }
public SampleStruct(int data)
{
_data = data;
}
#region IXmlSerializableMembers
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
this = new SampleStruct(int.Parse(reader.ReadString()));
}
public void WriteXml(XmlWriter writer
{
writer.WriteString(data.ToString());
}
#endregion
}
Since we're allowed to overwrite this, we can maintain the immutability of _data held within a single instance. This has the added benefit of when deserializing new values you're guaranteed a fresh instance, which is sometimes a nice guarantee!
}
You cannot overwrite "this". It points to the current object instance.