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
Related
For an object sellprint declared as static in the class
private static string sellprint = "";
public string Sellprint
{
get { return sellprint; }
}
public void SetSellprint(string x)
{
sellprint = x;
}
How is this
different from
public string Sellprint
{
get; set;
}
internally.
I could not find any examples of code 1 on msdn. what does it translate into?
The compiler creates a getter method for your property in the first code that returns the value of sellprint field because you implement only the getter method.In the second code, both getter and setter methods creating by compiler and also the backing-field.That's the difference.
You can verify that using ILDASM.exe:
First, consider this code:
class Foo
{
private string _value;
public string Value
{
get { return _value; }
}
public void SetValue(string str)
{
_value = str;
}
}
As you can see there is only one method generated by compiler which is get_Value.
If we change it like this and make the Value an auto-implemented property:
class Foo
{
public string Value { get; set; }
}
You can see that compiler creates both getter (get_Value) and setter (set_Value) method and also create a private backing field for the property.
There is no pros or cons about the functionality except in the second code you are doing the same work with less code.
1) should not work because there is no sellprint - assuming you have a field named sellprint and just forgot in your code snippet, you provide a get accessors and a method instead of the set accessors, which is kinda strange.
2) will create the field required automatically (and will not tell you the name, so you cannot accidentally use it)
There is not difference between those two though.
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.
I have class named "config" that have private string variable named "param".
I need to get from "config" class "param" variable sometimes as int type sometimes as bool type or string.
As I understand I need create 3 properties in config class,each property have to convert type, as follow:
The first property converts string to int, the second converts string to bool, the third property gets me the string value.
The class should look something like this:
class Config
{
private string param;
public int ParamAsInt
{
get
{
return int.Parse(param);
}
}
public bool ParamAsBool
{
get
{
return bool.Parse(param);
}
}
public string ParamAsString
{
get
{
return param;
}
}
}
But I don't know how can those properties be used in accordance to the variable type that I want to get out of class.
This code won't compile - int and such are reserved keywords and cannot be used as identifiers. You can either try naming your properties something like Int32Value, StringValue, etc., or try this:
public static implicit operator bool (Config config)
{
return bool.Parse(config.param);
}
public static implicit operator int (Config config)
{
return int.Parse(config.param);
}
This will allow for much cleaner code:
Config c = GetConfig("foo");
var isFeatureEnabled = false || c;
var spacing = 23 + GetConfig("bar");
You forgot to give your properties names. How would you expect to reference them? Something like this:
class Config
{
private string param;
public int ParamAsInt
{
get
{
return int.Parse(param);
}
}
public bool ParamAsBool
{
get
{
return bool.Parse(param);
}
}
public string ParamAsString
{
get
{
return param;
}
}
}
Note that I also fixed the casing in your calls to .Parse(). C# is case-sensitive. I also replaced the call to bool.TryParse() with bool.Parse(). The former (when used correctly, which this wasn't because it was missing a parameter) will only tell you if it is a bool, it won't tell you what value the bool actually has. (For example, bool.TryParse('false' out someBool) will return true.)
Of course, this code is a bit dangerous. You'll want to start with some more defensive programming to check those values. Basically, look up TryParse() and how to use it correctly. Something like this, for example:
public int ParamAsInt
{
get
{
var tmp = default(int);
if (int.TryParse(param, out tmp))
return tmp;
else
// do something else? throw a specific exception?
}
}
Additionally, what is the purpose of this code? It seems like a very rushed and poor design. For any given value of param (how is that even being set, by the way?) this just sort of randomly tries to expose typed properties for it. If you guess the correct one, you're still left with others that will throw exceptions. Surely there's a much cleaner way to accomplish what you're trying to do. So what are you trying to do?
Is there any difference between the two pieces of code below? Or is the top just a short form of the bottom one?
public string Name { get; set; }
and
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
The only difference (other than the fact you would have to do the initialization with "Default Name" in your class constructor) is that _Name will be visible within the class itself. There's a risk that the class will internally reference _Name rather than Name, everything will work fine, and at some later point in time you'll add some logic to Name that will not be called because you're using _Name within the class.
Example:
private string _Name = "Default Name";
public string Name
{
get { return _Name.Left(42); } // Changed the getter
set { _Name = value; }
}
void MyOtherMethod()
{
string foo = _Name; // Referencing the private field accidentally instead of the public property.
// Do something with foo
}
Basic behavior and purpose of both of the property method is almost same. But the major difference is in the implementation. The difference between
public string Name{get;set;}
AND
private string _Name;
public string Name
{
get { return _Name; }
set { _Name=value; }
}
is if you use short property syntax (introduced in framework 3.0 or later), then the property sting is never initialized i.e. if you directly use "Name" property anywhere without setting the value to it, it will return a NULL value. But if you use second syntax to initialize the property value, it will return a EMPTY string because when you initialize a string, it is initialized with a EMPTY value not the NULL. So if you return the property value without initializing using FULL Property Method, it will always return the EMPTY string not the NULL value.
I dont think there is any difference in compiled code. The reason why you may want to do the full way though is if you want to add a default value (which can be done in the constructor in short hand form), or add additional code to the getter or setter
EDIT: Actually, your code is wrong it should be
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }//change here
}
not...
value = _Name;
One difference is that you can set a default on the private string when you do this
private string _Name = "Default Name";
public string Name
{
get { return _Name; }
set { value = _Name; }
}
Once compiled the two examples you showed are the same.
It is simply a short form, the underlying variable is still generated as a supporting backing field (where the data is stored,) but automatically - this is useful if you are literally just getting and setting and don't need any specific implementation details in either accessor.
For this particular implementation of second form, both are equivalent. Because the compiler will generate almost the same code if you simply write the first form.
That is, the compiler is going to add code to it:
public string Name{get;set;}
making it look like this:
private string generatedCode_Name;
public string Name
{
get { return generatedCode_Name; }
set { generatedCode_Name = value; }
}
By the way, this is incorrect
set { value = _Name; } //I believe its a typo!
I think you meant:
set { _Name = value; }
For the example as written they are an exact equivalent.
Auto-implemented properties are syntactic sugar introduced to address exactly these type of situation, where the property is used just to avoid having a public field, with no extra logic in the getter/setter. However, an auto-implemented property gives you all the benefits of properties, including metadata. Here's a rather old but still relevant link that explains a little bit more about them.
Behind the scenes, the compiler generates a backing field very similar to your own.
I found the following syntax as a VB.NET property and I'm trying to convert it to c#, but I'm not sure how to accomplish that.
Public Property SomeText(ByVal someEnumThing as SomeEnum) As String
Get
Select Case someEnumThing
//figure out what string to return
End Select
End Get
Set(ByVal Value as String)
Select Case someEnumThing
//figure out what string to set
End Select
End Set
End Property
I've never seen a property done like this before, any ideas?
I guess you're referring to the arguments for the property. Well, as far as I know, C# only supports them for indexers, which cannot have a name (e.g. this[SomeEnum someEnumThing] {}).
If you want to get a similar behavior, you can create a helper class with an indexer property and use it to expose the "name" of the property:
public class YourClass {
public struct SomeTextProperty {
private readonly YourClass owner;
internal SomeTextProperty(YourClass owner) {
this.owner = owner;
}
public string this[SomeEnum someEnumThing] {
get {
return owner.GetSomeText(someEnumThing);
}
set {
owner.SetSomeText(someEnumThing, value);
}
}
}
public SomeTextProperty SomeText {
get {
return new SomeTextProperty(this);
}
}
private string GetSomeText(SomeEnum someEnumThing) {
// implementation to get it
}
private void SetSomeText(SomeEnum someEnumThing, string value) {
// implementation to set it
}
}
Hmm... maybe the switch statement?
It is impossible to create a Property in C# which has arguments, unless it's the default property:
public double this[int index]
{
get {...}
set {...}
}
Just one of those areas where VB differs from C#.
It is not recommended to use syntax like this since you will not be able to use that property from a C# project that references this assembly.
If you're talking about the fact that the property is parameterized...
There's no direct translation for this in c# that I know of. Basically this is carryover from VB6 where you could make this weird quasi-collection property for a class. The easiest way to get similar functionality is to create a dictionary object and either publicly expose it or create an accessor. Where the VB code accesses this property like Class.SomeText("SomeKey") your C# code will become Class.SomeDictionaryProperty["SomeKey"]
Unfortunately this still isn't quite the same since the collection accessor won't be able to "see" the index value. This has been a minor source of frustration for me as well in the past coming from a VB background.
The Select Case will be a switch statement. Is that what you are specifically referring to?
EDIT: here's what I was referring to in my comment to #Lucero's answer to get close to the VB.NET syntax.
private SomeEnum SomeEnumThing { get; set; }
public string SomeText {
get {
switch (SomeEnumThing) {
//figure out what string to return
}
}
set {
switch (SomeEnumThing) {
//figure out what string to set
}
}
}