Three operator causes StackOverflowException [duplicate] - c#

This question already has answers here:
Why does Property Set throw StackOverflow exception?
(3 answers)
Closed 6 years ago.
I know, I could simply use abs in this case, but I'm just curious: why is this happening?
public float maxThrotle{
set { maxThrotle = value < 0 ? -value : value; //this line causes problem
}
get { return maxThrotle; }
}

You are causing an infinite loop, by trying to call the property setter from within the property setter.
You probably want to create a private backing field to store the value, as follows:
private float maxThrotle;
public float MaxThrotle {
set { maxThrotle = value < 0 ? -value : value; //this line causes problem
}
get { return maxThrotle; }
}
Note I renamed the property to use a capital letter, in accordance with most C# coding standards.
(Also, the word throttle is spelled with double -t-).

Related

How to access property of a class whose name is in a variable [duplicate]

This question already has answers here:
How to get a property value based on the name
(8 answers)
Closed 3 years ago.
I have a class with is a collection of XPaths. I want to pass the name of the field and want to get the XPath for that field. The problem here is I have to store the passed value in a variable and putting an if condition to check for the corresponding XPath variable as shown below.
As of now, I am using the if condition and I can use switch condition as well but this solution is not feasible as the collection of XPath will grow and it will become unmanageable.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Program().IReturnXpath("LastName"));
}
public string IReturnXpath(String nameOfField)
{
if (nameOfField.Equals("Lastname"))
return new XpathCollection().Lastname;
else if (nameOfField.Equals("Firstname"))
return new XpathCollection().Firstname;
else
return "Xpath not found";
}
class XpathCollection
{
public string Lastname = "xpath for lastname";
public string Firstname = "xpath for firstname";
}
}
Let me explain how Microsoft solved exact same problem.
System.Drawing.Color has many properties each reflecting a single color. Color also has a FromName method which allows you to find a color by string parameter. Almost exactly your problem.
As you can see in their, implementation, they create a Hashtable and by using reflection they fill it. Next time someone asks for a color they just lookup and return it. Put generation code in a static constructor and you are done.
https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/ColorConverter.cs,d06a69beb42834b2

C# code effectiveness - calling a property tens of times

IDE: Visual Studio 2015 Update 3
Language: C# / .NET 4.5
Situation: Suppose I defined a class and I'm calling its properties tens of times, further let's suppose the class operates over one input given to the constructor and therefore it makes all operations except the first one redundant, because we already managed to calculate the return value the first time we called it.
Example of such property:
// let's call it a Month, because it extracts a month code from a string
private int Month
{
// there is only a getter
get
{
// here's my current strategy
// in the beginning of the class I set fMonth to -1
// it can only have possitive numbers, so if already set, I return it
if (fMonth > -1)
return fMonth;
// and here's the part I don't want to repeat
return fMonth =
Convert.ToInt32(SomeNumberString.Substring(2, 2));
}
}
Question: Is this the right strategy for not repeating the executive code?
Since the value for someNumberString is given to you in the constructor, you can use a readonly property.
ctor(string someNumberString)
{
Month = Convert.ToInt32(someNumberString.Substring(2, 2));
}
public Month { get; }
You are on the right track with using a private backing field fmonth for the property. You can further optimize this by moving the conversion code to an explicit set method. This removes the if check from every get access.
ctor(string someNumberString) {
SetMonth(someNumberString);
}
private int Month { get { return fmonth; } }
// -1 indicates that SetMonth() has never been called
private int fmonth = -1;
public void SetMonth(string someNumberString) {
fmonth = Convert.ToInt32(someNumberString.Substring(2, 2));
}

Disabling Case sensitivity for my keyword search [duplicate]

This question already has answers here:
Case insensitive 'Contains(string)'
(29 answers)
Closed 5 years ago.
I have a filter by text search in my wpf application. However when I do a string comparison to check if it contains a buzzword like, oh say "error", I want it to update/refresh my datagrid with all entries that have the Error keyword; regardless if I typed Error, or error, or eRRor in my search box.
Here is my code:
public class Foo
{
private void GetFilteredResults(MessageDetails detail, FilterEventArgs e)
{
foreach (MessageValue value in detail.MessageValue)
{
if (value.Value.Contains(txtFilterValue.Text))
{
//Returns true...
}
}
//Otherwise false
}
}
The Messagedetails is a container class and holds all of the datagrid row values.
The MessageValue is a struct that holds the actual message value in an ObservableCollection
Finally, the txtFilterValue is the control name of the textbox I am using to for my word filter
What I want to do is setup something to where I remove case sensitivity in order to cache all entries that match my keyword, regardless of how I type it. How would I go about that?
Let's say there is a boolean property CaseSensitive identifying the search mode. Then you can use string.IndexOf to solve this by setting the StringComparison correctly:
StringComparison comparison = CaseSensitive ?
StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
if (value.Value.IndexOf(txtFilterValue.Text, comparison) >= 0)
{
//Returns true...
}
The whole query can be simply written with LINQ like
private void GetFilteredResults(MessageDetails detail, FilterEventArgs e)
{
bool comparison = CaseSensitive ?
StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
return detail.MessageValue.Any(v => v.Value.IndexOf(txtFilterValue.Text, comparison) >= 0);
}

An interview riddle: accessing a private data member [duplicate]

This question already has answers here:
Access private fields
(4 answers)
Closed 6 years ago.
I recently had an interview with C# questions. One of them I cannot find an answer to.
I was given a class, looks like this:
public class Stick
{
private int m_iLength;
public int Length
{
get
{
return m_iLength;
}
set
{
if (value > 0)
{
m_iLength = value;
}
}
}
}
Also, a main class was given
static void Main(string[] args)
{
Stick stick = new Stick();
}
The task was to add code to the main that will cause m_iLength in the Stick class to be negative (and it was stressed out that it can be done).
I seem to miss something. The data member is private, and as far as I know the get and set function are by value for type int, so I do not see how this can be done.
Reflection is always the most direct:
var type = typeof(Stick);
var field = type.GetField("m_iLength", BindingFlags.NonPublic |BindingFlags.GetField | BindingFlags.Instance);
field.SetValue(stick, -1);
Console.WriteLine(stick.Length);
Explanation:
The first line gets the Type object for Stick, so we can get the private fields later on.
The second line gets the field that we want to set by its name. Note that the binding flags are required or field will be null.
And the third line gives the field a negative value.

Using Get and Set to set specific array elements [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I'm having problem with a school assignment in C#.
I include only a part of the code here, I hope that it suffices.
I'm creating an array of the Bottle class with index 25. The Bottle class contains three properties.
Now I need to get and set values in the array, but I don't manage to.
See my example below. Where am I doing wrong? The program doesn't show any errors but the compilation does not succeed. If any more code would be necessary I'm happy to give it!
public class Sodacrate
{
private Bottle[] bottles;
public Sodacrate() // Constructor for handling new sodas in the soda crate.
{
bottles = new Bottle[25];
bottles[0].Brand = "Fanta";
bottles[0].Price = 15;
bottles[0].Kind = "Soda";
}
}
public class Bottle
{
private string brand;
private double price;
private string kind;
public string Brand
{
get { return brand; }
set { brand = value; }
}
public double Price
{
get { return price; }
set { price = value; }
}
public string Kind
{
get { return kind; }
set { kind = value; }
}
}
There is no object at the zero index of the array. What you are doing is setting up memory for the array here:
bottles = new Bottle[25];
Then what you are doing is trying to set properties on the first object in that array here:
bottles[0].Brand = "Fanta";
bottles[0].Price = 15;
bottles[0].Kind = "Soda";
What is missing is the following:
bottles[0] = new Bottle();
So to summarize here is what you are doing:
//Give me a box big enough to hold 25 bottles
//Set the brand on the first bottle
This is what you should be doing:
//Give me a box big enough to hold 25 bottles
//Put the first bottle in the box
//Set the brand on the first bottle
Because Bottle is a reference type, so this statement will create an array contains 25 element with value is default value of reference type which is null.
bottles = new Bottle[25];
So, you must assign value to bottle[0] before use it. like this:
bottles[0] = new Bottle();

Categories

Resources