Integer Check with Ternary - c#

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.

Related

Can not use Func with parameters

I have an example for my problem.
Basically i need to pass a method to another method with parameters included.
public void test() {
var test = Add(Domath(5, 5)); // should be 10
}
public int Domath (int a, int b) {
return a + b;
}
public int Add (Func<int, int, int> math){
return math();
}
It does not work this way and i don‘t know why. This is just a minimalistic example. Is there a way to get this working?
Let's have a look at
public int Add (Func<int, int, int> math){
return math();
}
You can't return return math();: note, that math requires two arguments which are not passed to math(). You can modify Add as
public int Domath (int a, int b){
return a + b;
}
// We are going to add first and second
// with a help of math function
public int Add (int first, int second, Func<int, int, int> math = null) {
// If math is not provided, we use Domath functon
if (math == null)
math = Domath;
// Finally, we call math with required two arguments
return math(first, second);
}
Now you can put
public void test(){
var test = Add(5, 5);
}
Or
public void test(){
var test = Add(5, 5, Domath);
}

Convert any non integer or null value to 1

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;
}

Min and Max operations on enum values

Using C#, how can I take the min or max of two enum values?
For example, if I have
enum Permissions
{
None,
Read,
Write,
Full
}
is there a method that lets me do Helper.Max(Permissions.Read, Permissions.Full) and get Permissions.Full, for example?
Enums implement IComparable so you can use:
public static T Min<T>(T a, T b) where T : IComparable
{
return a.CompareTo(b) <= 0 ? a : b;
}
Since enums are convertible to integer types, you can just do:
var permissions1 = Permissions.None;
var permissions2 = Permissions.Full;
var maxPermission = (Permissions) Math.Max((int) permissions1, (int) permissions2);
Note that this could cause issues if your enum is based on an unsigned type, or a type longer than 32 bits (i.e., long or ulong), but in that case you can just change the type you are casting the enums as to match the type declared in your enum.
I.e., for an enum declared as:
enum Permissions : ulong
{
None,
Read,
Write,
Full
}
You would use:
var permissions1 = Permissions.None;
var permissions2 = Permissions.Full;
var maxPermission = (Permissions) Math.Max((ulong) permissions1, (ulong) permissions2);
can be called with 2 or more parameters
public static T GetMaxEnum<T>(params T[] enums) where T : struct, IConvertible
{
if (enums.Length < 2)
{
throw new InvalidEnumArgumentException();
}
return enums.Max();
}
This is what I came up with because I couldn't find anything in .NET that did this.
public static class EnumHelper
{
public static T Min<T>(T a, T b)
{
return (dynamic)a < (dynamic)b ? a : b;
}
public static T Max<T>(T a, T b)
{
return (dynamic)a > (dynamic)b ? a : b;
}
}
While this question is quite old, it shows up at the top for some searches I did, so here we go, with a little more detail than the existing answer:
Permissions p1 = Permissions.Read;
Permissions p2 = Permissions.Write;
var pMax = (Permissions)Math.Max( (int)p1, (int)p2 );
Alternatively in case the enum is long based:
var pMax = (Permissions)Math.Max( (long)p1, (long)p2 );
Why does this work?
enum values can be cast to int (or 'long'), which represents their position
An int can be cast back to an enum
Math.Max() apparently works on int
Sidenotes:
Appearently this also works for the mininum with Math.Min()
IEnumerable.Max() and IEnumerable.Min() can be used if you need the maximum or minimum of more than two enum values (if you don't mind System.Linq).
I think you want something like this:
public enum Enum1
{
A_VALUE,
B_VALUE,
C_VALUE
}
public enum Enum2
{
VALUE_1,
VALUE_2,
VALUE_3
}
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine(p.EnumMin<Enum1>());
Console.WriteLine(p.EnumMax<Enum2>());
}
T EnumMin<T>()
{
T ret; ;
Array x = Enum.GetValues(typeof(T));
ret = (T) x.GetValue(0);
return ret;
}
T EnumMax<T>()
{
T ret; ;
Array x = Enum.GetValues(typeof(T));
ret = (T)x.GetValue(x.Length-1);
return ret;
}
}
There is a one-stop means for getting the min and max for any enumeration. All it assumes is that the representation type is an int.
public Tuple<int,int> GetMinMaxOfEnumeration<T>()
{
if (!typeof (T).IsEnum)
{
throw new ArgumentException("Type must be an enumeration");
}
var valuesAsInt = Enum.GetValues(typeof (T)).Cast<int>().OrderBy(n => n).ToArray();
return new Tuple<int, int>(valuesAsInt.First(), valuesAsInt.Last());
}

How, if possible, can you pass in a C# Property to be used like a method?

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;
}

add(a,b) and a.add(b)

how can i transform a method (that performs a+b and returns the result) from add(a,b) to a.add(b)?
i read this somewhere and i can't remember what is the technique called...
does it depends on the language?
is this possible in javascript?
In .NET it is called extension methods.
public static NumberExtensions
{
public static int Add(this int a, int b)
{
return a + b;
}
}
UPDATE:
In javascript you could do this:
Number.prototype.add = function(b) {
return this + b;
};
var a = 1;
var b = 2;
var c = a.add(b);
On c# it is named extensions methods:
public static class IntExt
{
public static int Add(this int a, int b)
{
return a + b;
}
}
...
int c = a.Add(b);
say for example you want to do this on integers in C#. You need to define extension methods like this:
public static class IntExtMethods
{
public static int add(this int a, int b)
{
return a+b;
}
}
In C# you can use an Extension Method. In C++, you need to create a member which belongs to the A class which performs the add for you. C does not have objects, so what you're looking for is not possible in C.
If you want to create your own JavaScript class:
function Num(v) {
this.val = v;
}
Num.prototype = {
add: function (n) {
return new Num(this.val + n.val);
}
};
var a = new Num(1);
var b = new Num(2);
var c = a.add(b); // returns new Num(3);
Taking your question literally, I assume you mean transforming this
var add = function(a, b) {
return a + b;
}
to this:
a.add = function(b) {
return this + b;
}
This however only adds that method to a, not to any other object with the same constructor. See Darin Dimitrov's answer for an example of that. Extending the native Number constructor's prototype is not something many would recommend though...

Categories