Using Properties.Settings.Default as an argument for DisplayName - c#

I am attempting to store values for a displayName attribute from a setting held in the app.config file.
[System.ComponentModel.DisplayName(Properties.Settings.Default.field2Name)]
This does not work because it must be a constant value, which Properties.Settings.Default clearly is not. Is there any simple way to get around this?

Since the DisplayName property is virtual, you could do something like that:
public class DisplayNameSettingsKeyAttribute : DisplayNameAttribute
{
private readonly string _settingsKey;
public DisplayNameSettingsKeyAttribute(string settingsKey)
{
_settingsKey = settingsKey;
}
public string SettingsKey
{
get { return _settingsKey; }
}
public override string DisplayName
{
get { return (string)Properties.Settings.Default[_settingsKey]; }
}
}
And use it like that:
[DisplayNameSettingsKey("field2Name")]

Related

Is it possible to get the string of the name of a property in its get and set?

I want to store and retrieve my configs from database. I have written two methods setConfig(“configName”, value) and getConfig(“configName”) and I use them in my properties:
public long MyConfig1
{
get
{
return getConfig("MyConfig1");
}
set
{
setConfig("MyConfig1", value);
}
}
But I have to write the string of the name for all of properties.
Is it possible to get name or any reference to the current property in set and get in C#?
Something like this:
public long MyConfig1
{
get
{
return getConfig(getName(this));
}
set
{
setConfig(getName(this), value);
}
}
If you have access to the getConfig and setConfig methods, modify those methods as shown below. This is the most clean solution.
// using System.Runtime.CompilerServices;
public long MyConfig1
{
get
{
return getConfig();
}
}
private long getConfig([CallerMemberName] string propertyName = null)
{
}
However if you do not have access to modify those methods, use nameof in each setter and getter.
public long MyConfig1
{
get { return getConfig(nameof(MyConfig1)); }
}
You can write a method to use the caller-information attributes:
// Put this anywhere
public static string GetCallerName([CallerMemberName] name = null)
=> name;
Importantly, when you call this, don't supply an argument: let the compiler do it instead:
public long MyConfig1
{
get => GetConfig(Helpers.GetCallerName());
set => SetConfig(Helpers.GetCallerName(), value);
}
Or you could use the same attribute in the GetConfig and SetConfig methods, of course, and then just not supply an argument when you call them.

Could not evaluate expression: Activator.CreateInstance<T>()

I'm using Activator.CreateInstace() to create a generic instance. But when I use this to create a instance of an object:
public class SelectStageSaveData
{
public string GlobalPartnershipPoints { get; set; }
}
I get the message "Could not evaluate expression" when I'm debugging the code and trying to see GlobalPartnershipPoints. I've thought the value for this string were "empty" in this case, but I can't get any value. Does anyone know what is happening? Thanks in advance.
UPDATE:
Code where I create the instace:
if (!isolatedStorage.FileExists(file))
{
this.SaveData<T>((T)Activator.CreateInstance(typeof(T)), file);
}
or
if (!isolatedStorage.FileExists(file))
{
this.SaveData<T>(Activator.CreateInstance<T>(), file);
}
I get the same result with both.
I've thought the value for this string were "empty" in this case
Until you initialize the property, the value will be null by default. If you use a private field :
public class SelectStageSaveData
{
private string _GlobalPartnershipPoints = "";
public string GlobalPartnershipPoints
{
get { return _GlobalPartnershipPoints;}
set { _GlobalPartnershipPoints = value; }
}
}
Then you should get "" as default.
Hope it helps.

C# properties: how to use custom set property without private field?

I want to do this:
public Name
{
get;
set
{
dosomething();
??? = value
}
}
Is it possible to use the auto-generated private field?
Or is it required that I implement it this way:
private string name;
public string Name
{
get
{
return name;
}
set
{
dosomething();
name = value
}
}
Once you want to do anything custom in either the getter or the setter you cannot use auto properties anymore.
You can try something like this:
public string Name { get; private set; }
public void SetName(string value)
{
DoSomething();
this.Name = value;
}
As of C# 7, you could use expression body definitions for the property's get and set accessors.
See more here
private string _name;
public string Name
{
get => _name;
set
{
DoSomething();
_name = value;
}
}
This is not possible. Either auto implemented properties or custom code.
It is required that you implement it fully given your scenario. Both get and set must be either auto-implemented or fully implemented together, not a combination of the two.

How to use a a string of one class in another class?

I have a class in test.cs in which I have a string value string user="testuser". I want to use the test.cs's user value in another class. How can I do this?
Declare the string public:
public string user = "testuser";
Then you can access it from another class via
Test.user
However, depending on what exactly you want, you should perhaps make the field read-only:
public readonly string user = "testuser";
Or use a property, bound to a backing field:
public string User
{
get { return this.user; }
}
In fact, properties are the canonical way of making information accessible from the outside except for very few, very special cases. Public fields are generally not recommended.
As Ant mentioned in a comment, there is also the option of making it a constant (assuming it is, in fact, a constant value):
public const string user = "testuser";
Make a public property.
Public string TestUser
{
get { return testUser;}
}
You should make a property of user and expose this to any other class that want to read or write it's value.
class MyClass
{
private static string user;
public static string User
{
get { return user; }
set { user = value; }
}
}
class MyOtherClass
{
public string GetUserFromMyClass()
{
return MyClass.User;
}
}
public class AClass
{
// declarations
private string _user = "testUser";
// properties
public string User { get { return this._user;} set { this._user = value; } }
}
then call your class property, e.g.
AClass myClass = new AClass();
string sYak = myClass.User;
As suggested in the earlier answers, making "user" into a Property is the ideal technique of accomplishing this. However, if you want to expose it directly anyhow, you should use static to avoid having to instantiate an object of that class. In addition, if you don't want the demo class to manipulate the value of user, you should declare is readonly as well, like below
public static readonly user="text user";

C# Case-Insensitive String

Considering the class below
- can I do anything to implement a case-insensitive string?
public class Attibute
{
// The Name should be case-insensitive
public string Name
{
get;
set;
}
public Attibute()
{
}
}
public class ClassWithAttributes
{
private List<Attributes> _attributes;
public ClassWithAttributes(){}
public AddAttribute(Attribute attribute)
{
// Whats the best way to implement the check?
_attributes.add(attribute);
}
}
Structure of an HTML 4 Document
I have edited the class to be a bit more objective and specific
In answer to the restructured question, you could do it like this:
public class Attribute { public string Name { get; set; } }
public class AttributeCollection : KeyedCollection<string, Attribute> {
public AttributeCollection() : base(StringComparer.OrdinalIgnoreCase) { }
protected override string GetKeyForItem(Attribute item) { return item.Name; }
}
public class ClassWithAttributes {
private AttributeCollection _attributes;
public void AddAttribute(Attribute attribute) {
_attributes.Add(attribute);
//KeyedCollection will throw an exception
//if there is already an attribute with
//the same (case insensitive) name.
}
}
If you use this, you should either make Attribute.Name read-only or call ChangeKeyForItem whenever it's changed.
You can't have case-insensitive properties—you can only have case-insensitive operations, like a comparison. If someone accesses XHtmlOneDTDElementAttibute.Name, they will get back a string with whatever case it was created with.
Whenever you use .Name, you can implement that method in a way that ignores the case of the string.
It depends what you're trying to do with the strings.
If you want to compare strings regardless of case, call String.Equals with StringComparison.OrdinalIgnoreCase.
If you want to put them in a dictionary, make the dictionary's comparer StringComparer.OrdinalIgnoreCase.
Therefore, you could make a function as follows:
public class XHtmlOneDTDElementAttibute : ElementRegion {
public bool IsTag(string tag) {
return Name.Equals(tag, StringComparison.OrdinalIgnoreCase);
}
// The Name should be case-insensitive
public string Name { get; set; }
// The Value should be case-sensitive
public string Value { get; set; }
}
If you want a more specific solution, please tell me what you're doing with the Name property
Well, my take on this, after glancing at the spec, is that there's nothing you need to do to make the string properties case-insensitive. The concept doesn't really make sense, anyway: strings aren't case-sensitive or -insensitive; operations on them (like search and sort) are.
(I know the W3C's HTML recommendations say essentially that. It's badly-phrased.)
Alternatively, you might want to make the property always uppercase, like this.
public class XHtmlOneDTDElementAttibute : ElementRegion {
string name;
// The Name should be case-insensitive
public string Name {
get { return name; }
set { name = value.ToUpperInvariant(); }
}
// The Value should be case-sensitive
public string Value { get; set; }
}

Categories

Resources