I trying to create a custom Attribute to read a property and a value, here is the code, anyone knows how I can do this?
private string reason;
[CustomAttribute]
public string Reason
{
get
{
return reason;
}
set
{
// Read the reason and the value to the attribute
reason = value;
}
}
Related
Researched this error and some have said it's a bug but when I used some of their suggestions it didn't fix the problem. What should I do?
**Code
/// Indicates if the profiles has been added.
public Boolean _isNew
{
get { return _isNew; }
set { _isNew = value; }
}
/// Indicates if any of the fields in the class have been modified
public Boolean _isDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
//Gets and Sets delimiterChar
public Char _delimiterChar
{
get { return _delimiterChar; }
set { _delimiterChar = value;}
}
Error**
Ambiguity between 'ConsoleApplication3.ProfileClass.isNew'and 'ConsoleApplication3.ProfileClass.isNew
Ambiguity between 'ConsoleApplication3.ProfileClass.isDirty'and 'ConsoleApplication3.ProfileClass.isDirty
Ambiguity between 'ConsoleApplication3.ProfileClass._delimiterChar'and 'ConsoleApplication3.ProfileClass._delimiterChar
The code you have posted will cause recursion and eventual stackoverflow. You're trying to set property inside the property setter. You either need a backing field or automatic properties to achieve what you're doing. Something like:
private bool _isNew;
public Boolean IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
or
public Boolean IsNew {get; set;}
In C#, if you specify what you are getting and setting, you cannot use the same name as the property (self-reference issue). As of now, you are attempting to get and set a property to itself, which is not valid. Also a heads up about naming conventions, your public properties should not begin with an underscore, but should follow capital camel casing.
There are two answers to this, both equally valid depending on what you need to do.
METHOD 1: If you take out what it is getting and setting, C# can figure out that there is an implied field that is referenced by the IsNew property. This is essentially shorthand for METHOD 2.
public bool IsNew { get; set; } // shorthand way of creating a property
METHOD 2: Specify a field to get and set.
private bool _isNew; // the field
public bool IsNew { get => _isNew; set => _isNew = value; } // this is the property controlling access to _isNew
Read more information here: Shorthand Accessors and Mutators
Essentially, Use METHOD 1 by default if you don't need to perform any additional operations. However, if you need to provide additional functionality when getting or setting, then use METHOD 2 (I.E. look up the MVVM Pattern for an example https://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/)
I have some doubts on the auto-implemented property. Why do we first get, and then set the value?
What you've have posted is not an auto property.
Below is an example class that contains 1 auto property and a custom property similar to what you have done.
public class MyPropertyClass
{
public MyPropertyClass(bool affectLogic)
{
_affectLogic = affectLogic;
}
private readonly bool _affectLogic;
public string MyAutoProperty { get; set; }
private string _myPropertyWithLogic;
public string MyPropertyWithLogic
{
get
{
if (_affectLogic)
_myPropertyWithLogic = "Some value";
return _myPropertyWithLogic;
}
set
{
if (_affectLogic)
{
_myPropertyWithLogic = "Some value";
}
else
{
_myPropertyWithLogic = value;
}
}
}
}
The autoproperty "MyAutoProperty" provides a mechanism for simply getting and setting property values.
What you have posted in a standard property that allows you to perhaps manipulate or return the property value based upon certain conditions. In your post you are checking to see if the value posted in is null before setting.
If you do not need to access the property outside of the class then you do not need to have the get method. If you remove the get then you are creating a "WriteOnly" property which is bad practice.
Create a public method on the class that accepts the "Alert" value. If you dont need to access the property outside of the class then dont create a property at all.
public void SetMyProperty(string value)
{
_myPropertyWithLogic = value;
}
I know this might be a simple question but I was wondering in C# what is the best way to parse an incoming string within a set method to an int e.g. if I have
public int foo {get; set;}
On the set I want to parse a incoming string
There are a lot of ways to skin this cat. This is how I would do it.
Let's say your property is:
public int Foo
{
get { return _foo; }
set { _foo = value; }
}
You could do is add a helper method on your class:
public void SetFoo(string sFoo)
{
Foo = Convert.ToInt32(sFoo);
}
Then, when you need to set the value using a string, you can call that method:
myFooObject.SetFoo("4");
I guess you have some string and you want to parse it into int by setter. Of course, you can do it, but the property must be string.
private int foo
public string Foo
{
get
{
return foo.ToString();
}
set
{
foo = Int32.Parse(value);
}
}
But remember that Int32.Parse() throws an exception if your string is not a number. You should consider using Int32.TryParse() which could be a better choice in this case.
Do you mean this?
private int _foo;
public int Foo
{
get { return _foo; }
set
{
_foo = value;
ParseFoo(_foo);
}
}
but since you're talking about strings...
private string _foo;
public string Foo
{
get { return _foo; }
set {
_foo = value;
ParseIncomingString(_foo);
}
}
Well since the property is of type int, it's not possible to assign a string to it. So you need to do this parsing before assigning the value to your property.
Alternatively you could make your setter private, and have a public method that takes string, and do your validation inside of the method set the property if validation succeeds.
I would recommend you to make sure that your value is an int before you set it to your property when the set method is called automatically. This means that the string you want to set to your property should be parsed before it's set.
If you want to do it as you asked then you could simply use the Int32.Parse(value) or Int32.TryParse(value).
The difference between those two is that Parse(value) method throws an exception if the the parsing fails which means that you have to use try-catch block if you want to catch the exception and where TryParse(value) returns false if the parsing fails and true on success.
You can read more at: https://msdn.microsoft.com/en-us/library/bb397679.aspx
still new to C# and WPF and well I want to use an Enum but I can't figure out how to use it with OnPropertyChanged
public enum _status
{
AuthRequired, AuthAttempted, AuthReceived, AuthError, AuthSuccessful
}
this doesn't work:
public enum AuthStatus
{
get { return _status; }
set { ..... }
}
I know the solution is going to be very simple but i haven't found anything when I looked on google.. any help?
This simply will not work.
Part of the problem is that an enum, by definition, cannot set values, and for the normal use of enums you would never want to. This is simply how enums work.
Now, if your property in your model or viewmodel is an enum type, you can easily declare it as a property and raise property changes as with any other type.
private Status _status
public enum Status
{
AuthRequired, AuthAttempted, AuthReceived, AuthError, AuthSuccessful
}
public Status Status
{
get { return _status; }
set
{
_status = value;
RaisePropertyChanged("Status");
}
}
You can't declare an enum as a property. Your code needs to be:
private _status _myStatus;
public _status AuthStatus
{
get { return _myStatus; }
set
{
_myStatus = value;
NotifyPropertyChanged("AuthStatus")
}
}
Writing public enum _status declares a new type called _status (note this isn't a very good name for a type, since it looks like a private data member). You then need to declare a property and field of this type that you can then run NotifyPropertyChanged on.
Do I need to declare a class-level variable to hold a property, or can I just refer to self.{propertyname} in the getter/setter?
In other words, can I do this? (where I haven't defined mongoFormId anywhere):
public string mongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
You can either use automatic accessors or implement your own. If you use automatic accessors, the C# compiler will generate a backing field for you, but if you implement your own you must manually provide a backing field (or handle the value some other way).
private string _mongoFormId;
public string mongoFormId
{
get { return this._mongoFormId; }
set
{
this._mongoFormId = value;
revalidateTransformation();
}
}
UPDATE: Since this question was asked, C# 6.0 has been released. However, even with the new syntax options, there is still no way to provide a custom setter body without the need to explicitly declare a backing field.
You need to set a field variable and store the value there, if you're going to use custom getter and setter.
With the code you have right now you will be running into a stack overflow exception. When you assign something to mongoFormId, you'll execute the line this.MongoFormId = value;. This is an assignment to mongoFormId, resulting in executing the line this.MongoFormId = value;, and so on. It won't ever stop.
The correct way is a field:
private string _mongoFormId;
public string mongoFormId {
get { return this._mongoFormId; }
set {
this._mongoFormId = value;
revalidateTransformation();
}
}
You should have a backing variable. Take a closer look:
get { return this.mongoFormId; }
Is going to call the getter on mongoFormId, which will call that code again, and again, and again! Defining a backing variable will avoid the infinite recursive call.
Check MSDN Properties Overview
While a property definition generally includes a private data member,
this is not required. The get accessor could return a value without
accessing a private data member. One example is a property whose get
method returns the system time. Properties enable data hiding, the
accessor methods hide the implementation of the property.
You can do it both the ways.
If you want to have a class level member variable then do it this way -
public class sampleClass
{
private string _mongoFormId;
public string mongoFormId {
get { return _mongoFormId; }
set {
_mongoFormId = value;
revalidateTransformation();
}
}
}
Or do this simple in class, if no need for revalidateTransformation() execution call there
public class sampleClass
{
public string mongoFormId {get; set;}
}
This won't work since you get a recursive call to the property.
If I'm not mistaken, the result will be a StackOverflowException.
You must use a variable.
private string mongoFormId;
public string MongoFormId
{
get
{
return this.mongoFormId;
}
set
{
this.mongoFormId = value;
revalidateTransformation();
}
}
If you don't have to execute revalidateTransformation, you can use the auto-property.
This will create a backingfiled for you behind the scene.
public string MongoFormId { get; set; }
With the code you wrote, you are creating a recursive endless loop on both the get and set. The this keyword refer to the current class, not the property you are in.
So yes, you need to declare a private field. And to avoid confusion, create properties following the MSDN Naming Guideline (Use Pascal case for properties, camel case for private fields). And please do the same for your methods, it should be RevalidateTransformation instead of revalidateTransformation if you follow the C# convention instead of java's.
private string mongoFormId;
public string MongoFormId
{
get
{
return mongoFormId;
}
set
{
mongoFormId = value;
RevalidateTransformation();
}
}
public string mongoFormId {
get {
return this.mongoFormId;
}
set {
this.mongoFormId = value;
revalidateTransformation();
}
}
this way you have the Function recursive on all paths
The only way i see is to use a private data member. As other boys tells.