I wanted to write extension method which should return 1 if any non integer or null value is supplied. Int32.TryParse() parses non integer or null value to 0.
I have tried
public static int ToInt(this string text)
{
int num;
return int.TryParse(text, out num) ? num : 1;
}
just take an object, and test if it's an int:
static class Program
{
static void Main()
{
int i = "124241".ParseToInt(); //124241
int j = DateTime.Now.ParseToInt(); //-1
}
public static int ParseToInt(this object testItem)
{
int i;
return Int32.TryParse(testItem.ToString(), out i) ? i : -1;
}
}
1 typically means success. I wouldn't return 1 for a failure.
All you need to do is check if your parse succeeded or not and set the value appropriately.
var input = "blah";
int myInt;
bool parseSuccessful = Int32.TryParse(input, out myInt);
if (!parseSuccessful)
{
myInt = 1;
}
Related
I wrote a function that computes recursively the smallest divisor of an integer n>1:
using System;
public class Program
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(SmallestDivisor(n));
}
public static int SmallestDivisor(int n)
{
return SmallestDivisor(n, 2);
}
public static int SmallestDivisor(int n, int d)
{
if (n%d == 0)
return d;
else
return SmallestDivisor(n, d+1);
}
}
My goal is to build a recursive function that takes only the integer n as an argument. Is there any possible alternative to avoid calling another auxiliary function taking as arguments integer n and d?
There is no need for 2 method's one is just enough:
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(SmallestDivisor(n));
}
public static int SmallestDivisor(int n, int d=2)
{
if (n % d == 0)
return d;
return SmallestDivisor(n, ++d);
}
The parameter d is optinal because it has a default value of 2 and you can call the method like SmallestDivisor(n). If you want another value of d passed to the method just call SmallestDivisor(n,d).
replace
public static int SmallestDivisor(int n, int d)
with
public static int SmallestDivisor(int n, int d = 2)
To provide a default value for d and make this parameter optional. Now you can call SmallestDivisor(n) or SmallestDivisor(n,3)
Named and Optional Arguments
recursive method will throw StackOverflow exeption on relatively large prime number (e.g. 15331). non-recursive solution doesn't have such problem
public static int MinimalDivisor(int n)
{
if ( n % 2 == 0)
return 2;
for(int d = 3; d < n/2; d=d+2)
if (n % d == 0)
return d;
return n;
}
How to check for integer in one line?
sample.AddRange(Statistics.Select(player => new Stats
{
SeasonFromYear = Convert.ToInt32(seasonFromYear)
}
This one is working for me.
int a;
SeasonFromYear = int.TryParse(seasonFromYear, out a) ? a : default(int);
But for every property i need to declare one variable like a. Without that is it possible to check in one line?
Something like this
sample.AddRange(Statistics.Select(player => new Stats
{
SeasonFromYear = is integer ? then value : else default value
}
You can create extension method:
public static int ToInt(this string v)
{
int a = 0;
int.TryParse(v, out a);
return a;
}
And then:
int number = "123".ToInt();
Edit
Or you can pass integer as out parameter:
public static bool ToInt(this string v, out int a)
{
return int.TryParse(v, out a);
}
usage:
int number = 0;
"123".ToInt(out number);
That's not necessary. If int.TryParse fails, a will be set to default(int). Just use:
int a;
int.TryParse(sessionFromYear, out a);
SeasonFromYear = a;
Or if you really want to do it in one line, you'd have to create you're own wrapper method:
public static int TryParseInline(string in) {
int a;
int.TryParse(sessionFromYear, out a);
return a;
}
...
sample.AddRange(Statistics.Select(player => new Stats
{
SeasonFromYear = Util.TryParseInline(seasonFromYear),
...
})
Have you tried using a safe cast and doing a null-coalescing check in a single line?
SeasonFromYear = seasonFromYear as int ?? default(int);
Try:
int.TryParse(sessionFromYear, out SessionFromYear)
If SessionFromYear can be a property just create a method that will do what you need to do - e.g.:
public int ParseInt(string input)
{
int value;
int.TryParse(input, out value);
return value;
}
and then you can use this method all over the place like this:
SessionFromYear = ParseInt(sessionFromYear);
if you want to make it really fancy you could even create an extension method on the string class and then just do something like sessionFromYear.ToInt()
I know this is old but for one line just declare a in the TryParse:
SeasonFromYear = int.TryParse(seasonFromYear, out int a) ? a : default(int);
Put whatever default value you want where default(int) is.
I want to have a number (let's say i) whose range is between 0 to 26 so that when the number is 26 and it is incremented by 1 (say i++) the value returns to 0 (i.e. the value is circular).
Is there such a thing in c#? What is it called? If not then how would I implement this in code (overloaded operators are accepted).
Make a property that limits the value:
private int _value;
public int Value {
get { return _value; }
set { _value = value % 27; }
}
Now when you increase the property the setter will limit the value.
Example:
Value = 25;
Value++; // Value is now 26
Value++; // Value is now 0
Value++; // Value is now 1
You can try this:
int result = number % 27;
Use modulus operator (%)
var x = 0;
x = (x+1) % 27;
if you want it to go 0,1,2,3, ..... 24,25,26, 0, 1, 2, 3, ...
use modulus 27
I don't know of any sort of 'boundaries' or rules, you can "set" for an int in the way you want. I'd suggest creating an if statement, or two, to control it. `
if( i <= 26 & i >= 0)
{ ..do something..}
else i = 0;
Something like this should accomplish what you ask:
class CircularInt
{
public int value;
public static CircularInt operator ++(CircularInt c)
{
if (c.value >= 26)
c.value = 0;
else
c.value++;
return c;
}
}
Then use it:
CircularInt cInt = new CircularInt();
cInt++;
Console.WriteLine(cInt.value);
Another option is to define your own immutable type.
public struct Value27
{
private readonly int val;
private readonly bool isDef;
private Value27(int value)
{
while (value < 0) value += 27;
val = value % 27;
isDef = true;
}
public static Value27 Make(int value)
{ return new Value27(value); }
public bool HasValue { get { return isDef; } }
public int Value { get { return val; } }
public static Value27 operator +(Value27 curValue)
{ return Make(curValue.Value + 1); }
public static Value27 operator -(Value27 curValue)
{ return Make(curValue.Value + 26); }
public static implicit operator Value27(int bValue)
{ return Make(bValue); }
public static implicit operator int (Value27 value)
{ return value.Value; }
}
I am trying to write a function to convert the contents of a string "12345" to an int.
If the string is blank i would like to return null (uninitialized), not the value 0.
Problem is, functions do not return un-initialized values.
My code will not compile as Retval can return an uninitialized value......
My attempt so far:
public int ConvertStringToNumber(String TheString)
{
// Uninitialized
int Retval;
if (TheString.Length > 0)
{
// We have a valid string
if (Int32.TryParse(TheString, out Retval))
{
// We have a valid Number
}
}
// Return the number or null
return Retval;
}
Can you use Nullable int ? it will allow set as nullable . See here : http://www.codeproject.com/Articles/11854/C-2-0-Nullable-Types
You can use a nullable int (more info here).
Nullable types can represent all the values of an underlying type, and
an additional null value.
public int? ConvertStringToNumber(String TheString)
{
int retval;
bool isInt = Int32.TryParse(TheString, out retval);
return isInt ? retval : null;
}
Note: When using nullable types, you'll need to use a cast or get it's value. See here.
Example:
int? n = ConvertStringToNumber("123");
int value = n.Value;
// or
int value = (int)n;
If you assigned a value to the Retval object AT THE FIRST TIME, then the value is valid in THAT area ONLY.
So, Retval is null when you return it.
since Int32.TryParse(TheString, out Retval) require int type not nullable
public int? ConvertStringToNumber(String TheString)
{
// Uninitialized
int Retval;
if (TheString.Length > 0)
{
// We have a valid string
if (Int32.TryParse(TheString, out Retval))
{
// We have a valid Number
return Retval;
}
}
// Return the number or null
return null;
}
Simple extension method to resolve your problem
using System;
namespace temp
{
class Program
{
static void Main(string[] args)
{
string valu = "";
Console.WriteLine(valu.ToInt32());
Console.ReadLine();
}
}
public static class MyExtentions
{
public static int ToInt32(this string s)
{
int x;
if (s != null)
{
if (s.Length > 1)
x = Convert.ToInt32(s);
else
x = 0;
}
else
{
x= 0;
}
return x;
}
}
}
int? x = ConvertStringToNumber("1");
int value = x.Value;
String to numeric conversion in c#
I know Func<> is used to pass a method that has a return value to be used inside another method. I know Action<> is used to pass a method that does not have a return value to be used inside another method. Is there a way to pass in a property so it's get/set can be used inside another method?
For example, here is a method that uses Func<>:
public bool RangeCheck (int minVal, int maxVal, Func<< int, int >> someMethod)
{
bool retval = true;
try
{
for (int count = min; count <= max; count++)
{
int hello = someMethod(count);
}
}
catch
{
retval = false;
}
return retval;
}
What I am looking for is something like this:
public bool RangeCheck(int min, int max, Prop<< int >> someProperty)
{
bool retval = true;
try
{
for (int count = min; count <= max; count++)
{
someProperty = count;
}
}
catch
{
retval = false;
}
return retval;
}
Is there anything out there like this? I can't find anything. This would be very useful. Thanks.
Could you use a lambda as a wrapper?
MyClass myClass = new MyClass();
bool val = RangeCheck(0, 10, () => myClass.MyProperty);
If you're looking to do both, you would make two lambdas, one for set, and one for get.
bool val = RangeCheck(0, 10, () => myClass.MyProperty, (y) => myClass.MyProperty = y);
My syntax is probably off, but I think this gives the idea.
Not that I know of. You could try using reflection and pass the object along with the corresponding PropertyInfo object of the property you want to get the value of. You then call PropertyInfo's SetValue function to assign a value to it (assuming it's read/write, of course).
public void SetMyIntValue()
{
SetPropertyValue(this, this.GetType().GetProperty("MyInt"));
}
public int MyInt { get; set; }
public void SetPropertyValue(object obj, PropertyInfo pInfo)
{
pInfo.SetValue(obj, 5);
}
Why not simply make it a ref argument?
public bool RangeCheck(int min, int max, ref int someProperty)
You can now set the value of someProperty inside the method.
And call it like so:
RangeCheck(min, max, ref myProperty);
You could use a Func like this Func<int, T>
void Main()
{
var sc = new SimpleClass();
var result = RangeCheck(0, 10, x => sc.Value = x );
System.Console.WriteLine(result);
System.Console.WriteLine(sc.Value);
}
public class SimpleClass
{
public int Value { get; set; }
}
public bool RangeCheck<T>(int minVal, int maxVal, Func<int, T> someMethod)
{
bool retval = true;
try
{
for (int count = minVal; count <= maxVal; count++)
{
//someMethod(count); //is not a range check,
//Did you mean
someMethod(count - minValue);
}
}
catch
{
retval = false;
}
return retval;
}