Temporarily disable code contracts inside a block - c#

Is it possible to disable run time (and compile time) checks on a class using a method call or similar? I am having trouble with my classes with invariants and using them with external libraries that construct instances dynamically. I would like to wrap those calls inside my own calls, which take a potentially partially constructed object, and returns one that is always valid.
Eg consider this code:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ConsoleApp
{
class Person
{
public string Name { get; set; }
public string Email { get; set; }
public string JobTitle { get; set; }
public Person(string name, string email, string title)
{
Name = name;
Email = email;
JobTitle = title;
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(Name != null);
Contract.Invariant(JobTitle != null);
}
}
public static class ObjectBuilder
{
// Just a sample method for building an object dynamically. In my actual code, code using
// elastic search, NEST, serializion or entity framework has similar problems.
public static T BuildFromDictionary<T>(Dictionary<string, object> dict)
{
Contract.Requires(dict != null);
T result = (T)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof (T));
foreach (var pair in dict)
{
string propName = pair.Key;
var property = typeof (T).GetProperty(propName);
property.SetValue(result, pair.Value);
}
return result;
}
}
class Program
{
public static Person CreatePerson()
{
Dictionary<string, object> personData = new Dictionary<string, object>();
personData["Name"] = "Fred";
personData["Email"] = "email#example.com";
Person person = ObjectBuilder.BuildFromDictionary<Person>(personData);
person.JobTitle = "Programmer";
return person;
}
static void Main(string[] args)
{
Person person1 = new Person("Bob", "Bob#example.com", "Hacker");
Person person = CreatePerson();
Console.WriteLine(person.Name);
}
}
}
This compiles correctly, however will throw an exception on the property.SetValue(result, pair.Value); line. This is because it will call the Name setter, and at that stage Email and JobTitle are null.
What I would like to do is to disable contracts within a code section. Eg, replacing the CreatePerson method with something like this:
public static Person CreatePerson()
{
Dictionary<string, object> personData = new Dictionary<string, object>();
personData["Name"] = "Fred";
personData["Email"] = "email#example.com";
Person person;
Contract.DisableRunTimeChecks(() =>
{
person = ObjectBuilder.BuildFromDictionary<Person>(personData);
person.JobTitle = "Programmer";
});
Contract.CheckInvariants(person);
return person;
}
Where Contract.DisableRunTimeChecks disables run time checks for all code within that code block (and any calls made within), and Contract.CheckInvariants runs the ContractInvariantMethod for the given object.
Is this possible to implement somehow, or is there another solution?
One solution I have seen which I don't want to do is to introduce an _initialized field on Person, and making the invariant method check if that is true before doing any checks. This is because the object should always be valid except for one or two of these constructor methods.

The problem is with the way the invariants are defined. I posted an answer to a similar question here. Please read the answer to the question for the details, but here's a quick couple of paragraphs from that answer that's at the root of the issue here:
From the Code Contracts manual:
Object invariants are conditions that should hold true on each instance of a class whenever that object is visible to a client. They express conditions under which the object is in a "good" state.
There's a peculiar couple of sentences in the manual at the top of page 10:
Invariants are conditionally defined on the full-contract symbol [CONTRACT_FULL]. During runtime checking, invariants are checked at the end of each public method. If an invariant mentions a public method in the same class, then the invariant check that would normally happen at the end of that public method is disabled and checked only at the end of the outermost method call to that class. This also happens if the class is re-entered because of a call to a method on another class.
— text in brackets is mine; this is the compile time symbol the manual is referencing which is defined.
Since properties are really just syntactic sugar for T get_MyPropertyName() and void set_MyPropertyName(T), these sentences would seem to apply to properties, too. Looking in the manual, when they show an example of defining object invariants, they show using private fields in the invariant contract conditions.
So here's how you'll want to define the Person class:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ConsoleApp
{
class Person
{
private string _name;
private string _jobTitle;
// For consistency, I would recommend creating a
// private backing field for Email, too. But it's not
// strictly necessary.
public Person(string name, string email, string title)
{
// Are these pre-conditions strict enough??
// Maybe they are, but just asking.
Contract.Requires(name != null);
Contract.Requires(title != null);
_name = name;
_jobTitle = title;
Email = email;
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(_name != null);
Contract.Invariant(_jobTitle != null);
}
public string Name
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return _name;
}
set
{
Contract.Requires(value != null);
_name = value;
}
}
public string JobTitle
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return _jobTitle;
}
set
{
Contract.Requires(value != null);
_jobTitle = value;
}
}
public string Email { get; set; }
}
So to recap: Invariants only tell consumers what they can expect to be true about the object (at runtime) prior to calling any public method and upon any return from a public method. In this case, you're telling the consumer that you guarantee when they call a public method that Person.Name and Person.JobTitle will be non-null, and that when any public method returns to the caller, again, Person.Name and Person.JobTitle will be non-null. However, in order to ensure that these invariants can be maintained (and enforced), the class needs to state the pre-conditions and post-conditions when getting/setting the properties which mutate the values of the private backing fields _name and _jobTitle.

Related

Autofixture and read only properties

Let's consider two version (one with read only properties) of the same very simple entity:
public class Client
{
public Guid Id { get; set; }
public string Name { get; set; }
}
vs
public class Client
{
public Client(Guid id, string name)
{
this.Id = id;
this.Name = name;
}
public Guid Id { get; }
public string Name { get; }
}
When I try to use Autofixture, it will work correctly and as expected with both of them. The problems start, when I try to predefine one of the parameters using .with() method:
var obj = this.fixture.Build<Client>().With(c => c.Name, "TEST").Build();
This will throw error
System.ArgumentException: The property "Name" is read-only.
But it seems that Autofixture knows how to use constructors! And it seems that actual Build<>() method creates an instance of an object not Create()! If build would just prepare builder, with would setup properties, and then Create would instantiate object it would work properly with read only properties.
So why was this (misleading) strategy used here? I've found an answer here that states it's to amplify feedback with tests, but I don't see the usefulness to use FromFactory() especially when a list of parameters is extensive. Wouldn't moving object instantiation from Build() method to Create() method be more intuitive?
I too have struggled with this, since most of my classes are usually readonly. Some libraries like Json.Net use naming conventions to understand what are the constructor arguments that impact each property.
There is indeed a way to customize the property using ISpecimenBuilder interface:
public class OverridePropertyBuilder<T, TProp> : ISpecimenBuilder
{
private readonly PropertyInfo _propertyInfo;
private readonly TProp _value;
public OverridePropertyBuilder(Expression<Func<T, TProp>> expr, TProp value)
{
_propertyInfo = (expr.Body as MemberExpression)?.Member as PropertyInfo ??
throw new InvalidOperationException("invalid property expression");
_value = value;
}
public object Create(object request, ISpecimenContext context)
{
var pi = request as ParameterInfo;
if (pi == null)
return new NoSpecimen();
var camelCase = Regex.Replace(_propertyInfo.Name, #"(\w)(.*)",
m => m.Groups[1].Value.ToLower() + m.Groups[2]);
if (pi.ParameterType != typeof(TProp) || pi.Name != camelCase)
return new NoSpecimen();
return _value;
}
}
Trying to use this on the Build<> api was a dead end as you´ve noticed. So I had to create the extensions methods for myself:
public class FixtureCustomization<T>
{
public Fixture Fixture { get; }
public FixtureCustomization(Fixture fixture)
{
Fixture = fixture;
}
public FixtureCustomization<T> With<TProp>(Expression<Func<T, TProp>> expr, TProp value)
{
Fixture.Customizations.Add(new OverridePropertyBuilder<T, TProp>(expr, value));
return this;
}
public T Create() => Fixture.Create<T>();
}
public static class CompositionExt
{
public static FixtureCustomization<T> For<T>(this Fixture fixture)
=> new FixtureCustomization<T>(fixture);
}
which enabled me to use as such:
var obj =
new Fixture()
.For<Client>()
.With(x => x.Name, "TEST")
.Create();
hope this helps
AutoFixture is, indeed, capable of creating constructor arguments, and invoke constructors. How to control a particular constructor argument is a FAQ, so if that had been the only question, I'd had closed it as a duplicate of Easy way to specify the value of a single constructor parameter?
This post, however, also asks about the design choice behind the behaviour of the Build API, and I will answer that here.
In the second example, Name is a read-only property, and you can't change the value of a read-only property. That's part of .NET (and most other languages) and not a design choice of AutoFixture.
Let's be absolutely clear on this: Name is a property. Technically, it has nothing to do with the class' constructor.
I assume that you consider Name to be associated with the constructor's name argument, because one exposes the other, but we only know that because we have the source code. There's no technically safe way for an external observer to be sure that these two are connected. An outside observer, such as AutoFixture, could attempt to guess that such a connection exists, but there are no guarantees.
It's technically possible to write code like this:
public class Person
{
public Person(string firstName, string lastName)
{
this.FirstName = lastName;
this.LastName = firstName;
}
public string FirstName { get; }
public string LastName { get; }
}
This compiles just fine, even though the values are switched around. AutoFixture would be unable to detect issues like that.
It might be possible to give AutoFixture a heuristic where the Build API attempts to guess 'what you mean' when you refer to a read-only property, but back when I was still the benevolent dictator of the project, I considered that to be a feature with unwarranted complexity. It's possible that the new maintainers may look differently on the topic.
As a general observation, I consider the entire Build API a mistake. In the last many years I wrote tests with AutoFixture, I never used that API. If I still ran the project today, I'd deprecate that API because it leads people into using AutoFixture in a brittle way.
So this is very much an explicit design choice.
Hi I had a similar problem I solved it using `Freeze
_formFileMock = _fixture.Freeze<Mock<IFormFile>>();
_formFileMock.Setup(m => m.ContentType).Returns("image/jpeg");
_fixture.Create<P>

Cut down on repeated structure of Properties

I have a class with many automatic string properties representing a customer. Briefly, something like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
This data comes from clients and many different file imports using a Nuget package. Those clients appear to be copying their data out of a database-generated system where we get literal "NULL" strings sometimes in some fields. I'd like to strip those out in an easy fashion with a little change to existing code as possible. I don't want errors thrown, I just want it to be null instead of "NULL" (not a validation failure for Address2, but is for LastName).
Because there are many imports and I'm using a library off Nuget without the source, I can't really catch the data coming in. All of it ends up in a pretty small number of classes before we process it, so this seems like the place to do it. I list two fields here, but there are over a dozen, and it's not just one class. We also use ValueInjector a lot, so swapping out string for a custom class isn't really an option.
The best I can come up with is undoing the auto-properties and using a string extension method for the null check. That just seems like a whole lot of repeated bloat. Is there any way to define this action on a property and say do that every time without turning one line of code into thirteen dozens of times over?
public static class StringExtensions
{
public static string NullMeansNull(this string value)
{
if (value == "NULL")
return null;
else
return value;
}
}
public class Person
{
private string _FirstName;
public string FirstName
{
get
{
return this._FirstName.NullMeansNull();
}
set
{
this._FirstName = value;
}
}
private string _LastName;
public string LastName
{
get
{
return this._LastName.NullMeansNull();
}
set
{
this._LastName = value;
}
}
}
Note I'm not talking about code formatting. We have enough StyleCop and CodeAnalysis rules that keep things expanded similar to above, which is good when it's code you actually want to read.
I gave up trying not to touch each import. I just made a generic extension method I call after importing data that looks for any editable string property, checking for "NULL" or empty string and converting it to null.
public static T CleanNullishStrings<T>(this T obj) where T : class
{
foreach (System.Reflection.PropertyInfo property in obj.GetType().GetProperties())
{
if (property.PropertyType == typeof(string) && property.CanRead && property.CanWrite)
{
string value = (string)property.GetMethod.Invoke(obj, null);
value = string.IsNullOrEmpty(value) || value.ToUpper() == "NULL" ? null : value;
property.SetMethod.Invoke(obj, new object[] { value });
}
}
return obj;
}
Since it generically returns the object passed, I can use it in projections:
IEnumerable<Person> = personList.Select(p => p.CleanNullishStrings());

Property never null c#

When refactoring code, I come up with instances like the following
private string _property = string.Empty;
public string Property
{
set { _property = value ?? string.Empty); }
}
Later on in a method I see the following:
if (_property != null)
{
//...
}
Assuming that _property is only set by the setter of Property, is this code redundant?
I.e is there any way, through reflection wizardry or other methods that _property can ever be null?
Assuming that _property is only set by the setter of Property, is this
code redundant?
Exactly, it is redundant. This is the actual purpose of Properties. We shouldn't access the fields of a class directly. We should access them using a Property. So in the corresponding setter, we can embed any logic and we can rest assure that each time we try to set a value this logic would be verified once more.This argument holds even for the methods of a class. In a method we must use the properties and not the actual fields. Furthermore, when we want to read the value of a field, we should make use of the corresponding getter.
In general, properties enhances the concept of encapsulation, which is one of the pillars of object oriented programming OOP.
Many times there isn't any logic that should be applied when we want to set a value. Take for instance the following example:
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
We have declared a class for representing a Customer. A Customer object should have three properties an Id, a FirstName and a LastName.
An immediate question, when someones read this class is why should someone make use of properties here?
The answer is again the same, they provide a mechanism of encapsulation. But let's consider how can this help us in the long run. Let's say that one day someone decides that the first name of a customer should be a string of length less than 20. If the above class had been declared as below:
public class Customer
{
public int Id;
public string FirstName;
public string LastName;
}
then we should check for the length of FirstName in each instance we had created ! Otherwise, if we had picked the declaration with the properties, we could just easily make use of Data Annotations
public class Customer
{
public int Id { get; set; }
[StringLength(20)]
public string FirstName { get; set; }
public string LastName { get; set; }
}
and that's it. Another approach it could be the following:
public class Customer
{
public int Id { get; set; }
private string firstName;
public string FirstName
{
get { return firstName }
set
{
if(value!=null && value.length<20)
{
firstName = value;
}
else
{
throw new ArgumentException("The first name must have at maxium 20 characters", "value");
}
}
}
public string LastName { get; set; }
}
Consider both of the above approaches with having to revisit all your codebase and make this check. It's crystal clear that properties win.
Yes, it is possible through reflection. Nevertheless, I wouldn't worry about reflection -- people using reflection to defeat the design of your class is not something I worry about.
There is, however, something I do worry about: the phrase "Assuming that _property is only set by the setter of Property" is key. You are preventing users of your class from setting property to null.
You do not prevent, however, yourself or some other maintainer of your class from forgetting to only use the property INSIDE your class. In fact, your example has some one checking the field from inside the class rather than the property itself.... which means that, within your class, access comes from both the field and the property.
In most cases (where the problem could only come from inside the class) I would use an assertion and assert the field is not null.
If I really, really, really wanted to make sure that it wasn't null (barring reflection or people hell-bent on breaking things), you could try something like this:
internal class Program
{
static void Main()
{
string example = "Spencer the Cat";
UsesNeverNull neverNullUser = new UsesNeverNull(example);
Console.WriteLine(neverNullUser.TheString);
neverNullUser.TheString = null;
Debug.Assert(neverNullUser.TheString != null);
Console.WriteLine(neverNullUser.TheString);
neverNullUser.TheString = "Maximus the Bird";
Console.WriteLine(neverNullUser.TheString);
}
}
public class UsesNeverNull
{
public string TheString
{
get { return _stringValue.Value; }
set { _stringValue.Value = value; }
}
public UsesNeverNull(string s)
{
TheString = s;
}
private readonly NeverNull<string> _stringValue = new NeverNull<string>(string.Empty, str => str ?? string.Empty);
}
public class NeverNull<T> where T : class
{
public NeverNull(T initialValue, Func<T, T> nullProtector)
{
if (nullProtector == null)
{
var ex = new ArgumentNullException(nameof(nullProtector));
throw ex;
}
_value = nullProtector(initialValue);
_nullProtector = nullProtector;
}
public T Value
{
get { return _nullProtector(_value); }
set { _value = _nullProtector(value); }
}
private T _value;
private readonly Func<T, T> _nullProtector;
}
It is basically redundant. However, if it were mission critical or if for some reason it caused terrible side effects, it could remain. It is hard to tell, but part of your question was "can reflection change this value to null" to which the answer is yes and can be seen here in this linqpad demo
void Main()
{
var test = new Test();
test.Property = "5";
Console.WriteLine(test.Property);//5
FieldInfo fieldInfo = test.GetType().GetField("_property",BindingFlags.NonPublic | BindingFlags.Instance);
fieldInfo.SetValue(test, null);
Console.WriteLine(test.Property);//null
}
public class Test
{
private string _property = string.Empty;
public string Property
{
get { return _property; }
set { _property = value ?? string.Empty; }
}
}
I know this question is old, but look, I needed that one of my string properties never came up in null.
So I did this, and It worked for me
public string Operation { get; set; } = string.Empty;
In this way the default value is a string empty, but never null.

C# How to create special instances of a class?

For some classes, ideally, I'd like to create special named instances, similar to "null." As far as I know, that's not possible, so instead, I create static instances of the class, with a static constructor, similar to this:
public class Person
{
public static Person Waldo; // a special well-known instance of Person
public string name;
static Person() // static constructor
{
Waldo = new Person("Waldo");
}
public Person(string name)
{
this.name = name;
}
}
As you can see, Person.Waldo is a special instance of the Person class, which I created because in my program, there are a lot of other classes that might want to refer to this special well-known instance.
The downside of implementing this way is that I don't know any way to make all the properties of Person.Waldo immutable, while all the properties of a "normal" Person instance should be mutable. Whenever I accidentally have a Person object referring to Waldo, and I carelessly don't check to see if it's referring to Waldo, then I accidentally clobber Waldo's properties.
Is there a better way, or even some additional alternative ways, to define special well-known instances of a class?
The only solution I know right now, is to implement the get & set accessors, and check "if ( this == Waldo) throw new ..." on each and every set. While this works, I assume C# can do a better job than me of implementing it. If only I can find some C# way to make all the properties of Waldo readonly (except during static constructor.)
Make a private class inside the Person that inherits the Person, ImmutablePerson : Person.
Make all the property setters locked up: override them with NotImplementedException for instance.
Your static Person initialization becomes this:
public static readonly Person Waldo = new ImmutablePerson("Waldo");
And static constructor may be removed, too.
Maybe you could have the following hierarchy:
class Person
{
protected string _name;
public virtual string Name{
get{
return _name;
}
}
}
class EditablePerson:Person
{
public new string Name{
get{
return _name;
}
set{
_name=value;
}
}
public Person AsPerson()
{
//either return this (and simply constrain by interface)
//or create an immutable copy
}
}
In my opinion the best is to return always a new instance on Waldo. This way the original Waldo will never be changed. But this will prevent you from using reference equality for comparison, therefore you will have to override Equals and GetHashCode.
Thanks to all your suggestions - Here is the solution. I needed to make string virtual, override the accessors in a public derivative class, and use a bool flag to permit modification.
It's important to note, that "name" is a reference type, and although I've prevented changing what "name" refers to, if it were something other than a string, such as a class that contains a self-modification method, it could still be possible to modify the contents of the object, despite having prevented modification to the object reference.
class Program
{
static void Main(string[] args)
{
Person myPerson = new Person("Wenda");
System.Console.WriteLine("myPerson is " + myPerson.name); // Prints "myPerson is Wenda"
if (myPerson == Person.Waldo)
System.Console.WriteLine("Found Waldo (first attempt)"); // doesn't happen
else
System.Console.WriteLine("Still trying to find Waldo..."); // Prints "Still trying to find Waldo..."
myPerson.name = "Bozo";
System.Console.WriteLine("myPerson is now " + myPerson.name); // Prints "myPerson is now Bozo"
myPerson = Person.Waldo;
if (myPerson == Person.Waldo)
System.Console.WriteLine("Found Waldo (second attempt)"); // Prints "Found Waldo (second attempt)"
System.Console.WriteLine("myPerson is " + myPerson.name); // Prints "myPerson is Waldo"
System.Console.WriteLine("Now changing to The Joker..."); // Prints "Now changing to The Joker"
try
{
myPerson.name = "The Joker"; // throws ImmutablePersonModificationAttemptException
}
catch (ImmutablePersonModificationAttemptException)
{
System.Console.WriteLine("Failed to change"); // Prints "Failed to change"
}
System.Console.WriteLine("myPerson is now " + myPerson.name); // Prints "myPerson is now Waldo"
Thread.Sleep(int.MaxValue); // keep the console alive long enough for me to see the result.
}
}
public class Person
{
public static readonly ImmutablePerson Waldo = new ImmutablePerson("Waldo");
public virtual string name { get; set; }
public Person() // empty base constructor required by ImmutablePerson(string) constructor
{ }
public Person(string name)
{
this.name = name;
}
}
public class ImmutablePersonModificationAttemptException : Exception
{ }
public class ImmutablePerson : Person
{
private bool allowMutation;
protected string _name;
public override string name
{
get
{
return _name;
}
set
{
if (allowMutation)
_name = value;
else
throw new ImmutablePersonModificationAttemptException();
}
}
public ImmutablePerson(string name)
: base()
{
allowMutation = true;
this.name = name;
allowMutation = false;
}
}

C# Get property value without creating instance?

Is it possible to get value without creating an instance ?
I have this class:
public class MyClass
{
public string Name{ get{ return "David"; } }
public MyClass()
{
}
}
Now I need get the value "David", without creating instance of MyClass.
Real answer: no. It's an instance property, so you can only call it on an instance. You should either create an instance, or make the property static as shown in other answers.
See MSDN for more information about the difference between static and instance members.
Tongue-in-cheek but still correct answer:
Is it possible to get value without creating an instance ?
Yes, but only via some really horrible code which creates some IL passing in null as this (which you don't use in your property), using a DynamicMethod. Sample code:
// Jon Skeet explicitly disclaims any association with this horrible code.
// THIS CODE IS FOR FUN ONLY. USING IT WILL INCUR WAILING AND GNASHING OF TEETH.
using System;
using System.Reflection.Emit;
public class MyClass
{
public string Name { get{ return "David"; } }
}
class Test
{
static void Main()
{
var method = typeof(MyClass).GetProperty("Name").GetGetMethod();
var dynamicMethod = new DynamicMethod("Ugly", typeof(string),
Type.EmptyTypes);
var generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Ldnull);
generator.Emit(OpCodes.Call, method);
generator.Emit(OpCodes.Ret);
var ugly = (Func<string>) dynamicMethod.CreateDelegate(
typeof(Func<string>));
Console.WriteLine(ugly());
}
}
Please don't do this. Ever. It's ghastly. It should be trampled on, cut up into little bits, set on fire, then cut up again. Fun though, isn't it? ;)
This works because it's using call instead of callvirt. Normally the C# compiler would use a callvirt call even if it's not calling a virtual member because that gets null reference checking "for free" (as far as the IL stream is concerned). A non-virtual call like this doesn't check for nullity first, it just invokes the member. If you checked this within the property call, you'd find it's null.
EDIT: As noted by Chris Sinclair, you can do it more simply using an open delegate instance:
var method = typeof(MyClass).GetProperty("Name").GetGetMethod();
var openDelegate = (Func<MyClass, string>) Delegate.CreateDelegate
(typeof(Func<MyClass, string>), method);
Console.WriteLine(openDelegate(null));
(But again, please don't!)
You can make that property static
public static string Name{ get{ return "David"; } }
Usage:
MyClass.Name;
You requirements do seem strange, but I think you're looking for some kind of metadata. You can use an attribute to achieve this:
public class NameAttribute : Attribute {
public string Name { get; private set; }
public NameAttribute(string name) {
Name = name;
}
}
[Name("George")]
public class Dad {
public string Name {
get {
return NameGetter.For(this.GetType());
}
}
}
[Name("Frank")]
public class Son : Dad {
}
public static class NameGetter {
public static string For<T>() {
return For(typeof(T));
}
public static string For(Type type) {
// add error checking ...
return ((NameAttribute)type.GetCustomAttributes(typeof(NameAttribute), false)[0]).Name;
}
}
Now this code can get names with and without instances:
Console.WriteLine(new Dad().Name);
Console.WriteLine(new Son().Name);
Console.WriteLine(NameGetter.For<Dad>());
Console.WriteLine(NameGetter.For<Son>());
You can make your property static, as pointed out by many others.
public static string Name{ get{ return "David"; } }
Be aware that this means your instances of MyClass will no longer have their own Name property, since static members belong to the class, not the individual object instances of it.
Edit:
In a note, you mentioned that you want to override the Name property in subclasses. At the same time, you want to be able to access it at the class level (access it without creating an instance of your class).
For the static properties, you would simply create a new Name property in each class. Since they are static, you're always (almost always, yay reflection) going to access them using a specific class, so you'd be specifying which version of Name you want to get. If you want to try and hack polymorphism in there and get the name from any given subclass of MyClass, you could do so using reflection, but I wouldn't recommend doing so.
Using the example from your comment:
public class Dad
{
public static string Name { get { return "George"; }
}
public class Son : Dad
{
public static string Name { get{ return "Frank"; }
}
public static void Test()
{
Console.WriteLine(Dad.Name); // prints "George"
Console.WriteLine(Son.Name); // prints "Frank"
Dad actuallyASon = new Son();
PropertyInfo nameProp = actuallyASon.GetType().GetProperty("Name");
Console.WriteLine(nameProp.GetValue(actuallyASon, null)); // prints "Frank"
}
As a side note, since you are declaring a property that has only a getter and it is returning a constant value, I recommend possibly using a const or static readonly variable instead.
public const string Name = "David";
public static readonly string Name = "David";
Usage for both would be the same:
string name = MyClass.Name;
The main benefit (and drawback) of const is that all references to it are actually replaced by its value when the code is compiled. That means it will be a little faster, but if you ever change its value, you will need to recompile ALL code that references it.
Whenever you write C# code, always check if your method and property getter/setter code does anything at all with other instance members of the class. If they don't, be sure to apply the static keyword. Certainly the case here, it trivially solves your problem.
The reason I really post to this question is that there's a bit of language bias at work in some of the answers. The C# rule that you can't call an instance method on a null object is a specific C# language rule. It is without a doubt a very wise one, it really helps to troubleshoot NullReferenceExceptions, they are raised at the call site instead of somewhere inside of a method where it gets very hard to diagnose that the this reference is null.
But this is certainly not a requirement to the CLR, nor of every language that run on the CLR. In fact, even C# doesn't enforce it consistently, you can readily bypass it in an extension method:
public static class Extensions {
public static bool IsNullOrEmpty(this string obj) {
return obj != null && obj.Length > 0;
}
}
...
string s = null;
bool empty = s.IsNullOrEmpty(); // Fine
And using your property from a language that doesn't have the same rule works fine as well. Like C++/CLI:
#include "stdafx.h"
using namespace System;
using namespace ClassLibrary1; // Add reference
int main(array<System::String ^> ^args)
{
MyClass^ obj = nullptr;
String^ name = obj->Name; // Fine
Console::WriteLine(name);
return 0;
}
Create a static property:
public class MyClass
{
public static string Name { get { return "David"; } }
public MyClass()
{
}
}
Get it like so:
string name1 = MyClass.Name;
That is not possible. As Name is an instance property, you can only get its value if you have an instance.
Also, note that you are not talking about a parameter, but about a property.
Create a static class or a static property, and you don't have to explicitly instantiate it.

Categories

Resources