I am converting a Delphi code to a C#.
I have a complex classes structure where a class is the main ‘trunk’ of all its children.
In Delphi I can define the private/protected field with a type and the property for that field with the same type, and not write the type in child classes anymore.
Here is a bit (and functional) example:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
Parent = class
strict protected
_myFirstField: Int64;
public
property MyFirstField: Int64 write _myFirstField;
end;
Child1 = class(Parent)
public
// Inherits the write/set behaviour..
// And it doesn't need to define the type 'over and over' on all child classes.
//
// ******* Note MyFirstField here has not type.... ************
property MyFirstField read _myFirstField; // Adding READ behaviour to the property.
end;
var
Child1Instance: Child1;
begin
Child1Instance := Child1.Create;
//Child1Instance.MyFirstField := 'An String'; <<-- Compilation error because type
Child1Instance.MyFirstField := 11111;
WriteLn(IntToStr(Child1Instance.MyFirstField));
ReadLn;
end.
As you can see I don’t need to define the property type over and over.
If I need to change the var type in the future, I can change only in the parent class.
Is there any way to get this same behaviour in C#?
No, there ist. The types on the public API must be explicit. The only time you aren’t explicit is with
var, which is limited to method variables.Further, you can’t change the signature in C# (adding a public getter in the subclass) – you would have to re-declare it:
But as the
newsuggests: this is an unrelated property and is not required to have the same type.