Is There a C# in Operator

Is there a C# IN operator?

If you wanted to write .In then you could create an extension that allows you to do that.

static class Extensions
{

public static bool In<T>(this T item, params T[] items)
{
if (items == null)
throw new ArgumentNullException("items");

return items.Contains(item);
}

}

class Program
{

static void Main()
{

int myValue = 1;

if (myValue.In(1, 2, 3))
// Do Somthing...

string ds = "Bob";

if (ds.In("andy", "joel", "matt"))
// Do Someting...
}
}

in operator in C#

Try this:

if(new [] {"a", "b", "c"}.Contains(aString))  
Console.Out.WriteLine("aString is 'a', 'b' or 'c'");

This uses the Contains method to search the array for aString.

Difference Between in Operator and Simple Value Pass c#

The following clearly explains the purpose :

passes a variable in to a method by reference. Cannot be set inside the method.

From Official DOCS:

The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method.

The only difference is that the incoming parameters value cannot be set within the method when parameters are having in operator while in normal parameters we can set whatever value we want, using in we restrict from doing that.

For example:

 public static int Add(in int number1, in int number2)
{
number1 = 2; // this will give compile time error as we cannot set it.
return number1 + number2;
}

while in normal case we can set whenever we want though in the example it does not makes sense to set but clearly explains the difference:

 public static int Add(int number1,int number2)
{
number1 = 2; // this works.
return number1 + number2;
}

So, we can say that the method parameters become immutable technically.

You can read more details about it here.

What is the with operator for in C#?

It's an operator used in expressions for easier duplication of an object, overriding some of it's public properties/fields (optional)
with expression - MSDN

Currently it can only be used with records. But maybe there will be no such restriction in the future (assumption).

Here's an example how it can be used:

// Declaring a record with a public property and a private field
record WithOperatorTest
{
private int _myPrivateField;

public int MyProperty { get; set; }

public void SetMyPrivateField(int a = 5)
{
_myPrivateField = a;
}
}

Now let's see how with operator can be used:

var firstInstance = new WithOperatorTest
{
MyProperty = 10
};
firstInstance.SetMyPrivateField(11);
var copiedInstance = firstInstance with { };
// now "copiedInstance" also has "MyProperty" set to 10 and "_myPrivateField" set to 11.

var thirdCopiedInstance = copiedInstance with { MyProperty = 100 };
// now "thirdCopiedInstance " also has "MyProperty" set to 100 and "_myPrivateField" set to 11.

thirdCopiedInstance.SetMyPrivateField(-1);
// now "thirdCopiedInstance " also has "MyProperty" set to 100 and "_myPrivateField" set to -1.

NOTE for reference types from MSDN:

In the case of a reference-type member, only the reference to a member instance is copied when an operand is copied. Both the copy and original operand have access to the same reference-type instance.

That logic can be modified by modifying the copy constructor of a record type. Quote from MSDN:

By default, the copy constructor is implicit, that is, compiler-generated. If you need to customize the record copy semantics, explicitly declare a copy constructor with the desired behavior.

protected WithOperatorTest(WithOperatorTest original)
{
// Logic to copy reference types with new reference
}

And in terms of what benefits it gives, I think it should be quite obvious now, that it makes copying of instances much easier and convenient.

Is there an OR operator in C# conditional compilation?

Yes there is. It's the same as in a standard if:

#if NET45
// ...
#elif (NETCOREAPP2_1 || NETCOREAPP3_0)
// ...
#endif

More here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if

C# '|' operator and arguments

Yes, | is the (bitwise) OR operator in C#. In PowerShell, however, | is the "pipe" operator to connect the output of one cmdlet to the input of another. The binary OR operator in PowerShell is -bor.

Also see about_Operators.

Need in IS operator in C#

why do we need is operator?

We don't need it. It is redundant. If the is operator were not in the language you could emulate it by simply writing

(x as Blah) != null

for reference types and

(x as Blah?) != null

for value types.

In fact, that is all is is; if you look at the IL, both is and as compile down to the same IL instruction.

Your first question cannot be answered because it presumes a falsehood. Why do we need this operator? We don't need it, so there is no reason why we need it. So this is not a productive question to ask.

Which are the cases when is operator is more preferable over as.

I think you meant to ask

why would I write the "inefficient" code that does two type checks -- is followed by a cast -- when I could write the efficient code that does one type check using as and a null check?

First of all, the argument from efficiency is weak. Type checks are cheap, and even if they are expensive, they're probably not the most expensive thing you do. Don't change code that looks perfectly sensible just to save those few nanoseconds. If you think the code looks nicer or is easier to read using is rather than as, then use is rather than as. There is no product in the marketplace today whose success or failure was predicated on using as vs is.

Or, look at it the other way. Both is and as are evidence that your program doesn't even know what the type of a value is, and programs where the compiler cannot work out the types tend to be (1) buggy, and (2) slow. If you care so much about speed, don't write programs that do one type test instead of two; write programs that do zero type tests instead of one! Write programs where typing can be determined statically.

Second, there are situations in C# where you need an expression, not a statement, and C# unfortunately does not have "let" expressions outside of queries. You can write

... e is Manager ? ((Manager)e).Reports : 0 ...

as an expression but pre C# 7 there was no way to write

Manager m = e as Manager;

in an expression context. In a query you could write either

from e in Employees
select e is Manager ? ((Manager)e).Reports : 0

or

from e in Employees 
let m = e as Manager
select m == null ? 0 : m.Reports

but there is no "let" in an expression context outside of queries. It would be nice to be able to write

... let m = e as Manager in m == null ? 0 : m.Reports ...  

in an arbitrary expression. But we can get some of the way there. In C# 7 you'll (probably) be able to write

e is Manager m ? m.Reports : 0 ...

which is a nice sugar and eliminates the inefficient double-check. The is-with-new-variable syntax nicely combines everything together: you get a Boolean type test and a named, typed reference.

Now, what I just said is a slight lie; as of C# 6 you can write the code above as

(e as Manager)?.Reports ?? 0

which does the type check once. But pre C# 6.0 you were out of luck; you pretty much always had to do the type check twice if you were in an expression context.

C# What is the '?' operator

In this case ? is not an operator. It is a shorter way to write: Nullable<long>

T? is exactly the same as Nullable<T> (with T a type)

It is called a nullable type (see MSDN)

It is used to allow "non-nullable" type (like int, long, a struct) to be assigned a null value.

It is useful when you need a possible invalid state for a value type, or if the data is being retrieved from a database that may contain a null value.

Is there any compare operator in c# like SQL's IN statement

tickets.Where(t => new[] {"Open",
"Active",
"Reopen",
"InActive"}.Any(x => x == t.status))

You can also use the Contain method instead of the Any method, but use the Any method if there's any comparement logic you would like to implement, instead of the default equality comparer.

OR

Implement extensions to support IN method:

public static class Extensions
{
public static bool In<TItem>(this TItem source, Func<TItem, TItem, bool> comparer, IEnumerable<TItem> items)
{
return items.Any(item => comparer(source, item));
}

public static bool In<TItem, T>(this TItem source, Func<TItem, T> selector, IEnumerable<TItem> items)
{
return items.Select(selector).Contains(selector(source));
}

public static bool In<T>(this T source, IEnumerable<T> items)
{
return items.Contains(source);
}

public static bool In<TItem>(this TItem source, Func<TItem, TItem, bool> comparer, params TItem[] items)
{
return source.In(comparer, (IEnumerable<TItem>)items);
}

public static bool In<TItem, T>(this TItem source, Func<TItem, T> selector, params TItem[] items)
{
return source.In(selector, (IEnumerable<TItem>)items);
}

public static bool In<T>(this T source, params T[] items)
{
return source.In((IEnumerable<T>)items);
}
}

And use like this:

bool b;

b = 7.In(3, 5, 6, 7, 8); // true
b = "hi".In("", "10", "hi", "Hello"); // true
b = "hi".In("", "10", "Hi", "Hello"); // false
b = "hi".In((s1, s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase), "", "10", "Hi"); // true

var tuples = new List<Tuple<int, string>>();

for (var i = 0; i < 10; i++)
{
tuples.Add(Tuple.Create(i, ""));
}

var tuple = Tuple.Create(3, "");

b = tuple.In(tup => tup.Item1, tuples); // true


Related Topics



Leave a reply



Submit