Var, Ternary Operator And LINQ In C#

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 9, 2024

This tutorial explains the Var, LINQ and Ternary Operator in C# with syntax, usage and programming examples:

C# is a strongly typed language i.e. we need to declare a variable before we can use it anywhere in the program. But let’s assume a scenario where we don’t know what variable type we will be needing in the next step of the program.

To handle these types of scenarios, C# allows the user to declare variables without providing any explicit data types to them. This can be achieved by declaring a “var” type variable.

=> Read Through The Easy C# Training Series

Var ,ternary operator and LINQ in C#

C# Var

Characteristics Of “var” Keyword

The var keyword initializes variables with support from var. The data type of a var variable is defined during the execution time while assigning data to the variable. C# automatically casts the data type to the var variable. Once the data type has been assigned to the variable, it cannot be changed.

Example

The “var” keyword can be used to declare a var type variable that can be used to store any data type. Let’s have a look at some of the uses of var type variables for the different data types.

        public static void Main(string[] args)
        {

            var integerData = 100;
            var booleanData = true;
            var stringData = "Var Keyword";
            Console.WriteLine("Printing different var variables: \n{0}\n{1}\n{2}", integerData, booleanData, stringData);
            Console.Read();

        }

Output

Printing different var variables:
100
True
Var Keyword

Explanation

Here we defined 3 different variables – integerData, booleanData and stringData with “var” data type. Then we assigned values of different data types to each of these variables. Now if we print this to the console, then we will get the output of all the assigned values.

Using var To Access Data From ArrayList

Let’s assume that we have an ArrayList that we want to access. If we don’t have any idea about the data type of the array list then using a var variable can be quite useful. It can also be helpful if the array list comprises of multiple data types.

Example

        public static void Main(string[] args)
        {

            ArrayList ar = new ArrayList();
            ar.Add(1);
            ar.Add(2);
            ar.Add(3);
            ar.Add(4);
        
            foreach (var a in ar)
            {
                Console.WriteLine(a);
            }
            Console.Read();

        }

Output

1
2
3
4

Explanation

We created an ArrayList with 4 values 1, 2, 3, and 4. As already mentioned, if we don’t know the data types present in the Array list then we can use a “var” in the foreach loop to access any data type it may contain.

So, each variable will be assigned data types at the time of value assignment. This is also useful if the array contains multiple data type values.

Restrictions With Using var

Similar to the other data types and keywords var also has its fair share of restrictions. Let’s have a look at some of the constraints for the var keyword.

  • Var obfuscates the actual data type of the variable. If an initializer somehow doesn’t assign a clearly defined data type, then it will be difficult to determine the actual data type of the variable.
  • The keyword ‘var’ is simply that the programmers end up using it everywhere and that makes it difficult to differentiate it from the other variables in the application. For example, if I have a var type variable. I don’t know if it’s a string, integer, or even a dictionary.

Summary Of The C# var Keyword

Enlisted below are some of the most important facts about var keyword that we all need to keep in mind while using it:

  • Var is quite useful in defining variables locally without having to provide an explicit data type. The data type of a var variable is determined while any value is assigned to it. Once a data type has been assigned, it cannot be changed.
  • All the var variables must be declared and initialized in the same line of code. C# doesn’t allow assigning a null value to the implicit local variables.

C# Ternary Operators

The ternary operator in C sharp is a decision-making operator and it substitutes the if-else statement in C sharp programming language. This operator allows us to replace multiple if-else statements into a simple line of code.

A ternary operator helps the programmers to execute statements based on some predefined conditions by using the decision-making operator syntax “?:”.

Syntax Of The Ternary Operator

In C# programming language, the ternary operator contains 3 different types of operands

Condition_expression ? First_expression: Second_expression;

As seen in the above syntax, the ternary operator is composed of three parts. The first part contains a conditional expression that will return a Boolean value i.e. True or false.

The second part contains the statement that a programmer wants to return if the expression is evaluated as true. The final and the last part contains the statement that will be returned if the expression evaluates as false.

The point to keep in mind is that the ternary operator only returns the value contained in the second and third parts it does not execute the expressions.

Let’s look at the following example to see how a conditional operator works:

Program

public static void Main(string[] args)
        {

            int a = 1;
            int b = 3;

            var compare = a > b ? "a is greater than b " : "b is greater than a";

            Console.WriteLine("The comparison result : {0}", compare);

        }

Output

The comparison result: b is greater than a

Explanation of code

Here, we have two different integers that we used for comparison. We use a var compare to store the result. Then we use a ternary operator to compare both integers. So, if the expression returns true then the first statement will be returned as a result and if the expression is false then the second statement will be returned.

Nested Ternary Operator

C# also allows programmers to create a nested ternary operator by combining multiple conditional expressions. The nested ternary operator helps in replacing multiple if-else if statements and thereby simplifies them into a single line of code.

Let’s see an example to standard nested ternary more clearly. For example, we will discuss how we can use a single line of code of the ternary operator instead of using a large if-else-if statement block.

Program

public static void Main(string[] args)
        {

            int a = 3;
            int b = 3;

            var compare = a > b ? "a is greater than b" : a < b ?
                            "a is less than b" : a == b ?
                            "a is equal to b" : "Some error/No value returned";

            Console.WriteLine("The comparison result : {0}", compare);

        }

Output

The comparison result: a is equal to b

Explanation

If we look at the above example we will be able to see that instead of writing multiple if-else statements we have written a single nested ternary operator that gives the same result as multiple statements written above that.

A nested ternary operator is written by replacing the second statement in the ternary operator syntax with another ternary operator. We can do this several times to nest any number of the given condition. This can also be used to replace the if else if condition.

Summary Of The Ternary Operator

  • We learned about the ternary operator expression.
  • We also learn that a ternary operator always returns a value and it is not executed.

Free- ternary operator can be used to replace if-else or if-else-if statements. We can simply use a ternary operator or we can even use a nested ternary operator.

C# LINQ

A language integrated query or LINQ was introduced in .net Framework 3.5. It helps in querying data from different data collectors such as database collections etc. Based on the user requirements.

It’s integrated with both C Sharp and VB, thereby helping in removing the conflict between the different programming languages and databases at the same time, thereby providing a single language query for different data sources.

For example, we can use a LINQ to retrieve unsaved data from the database similar to SQL Query. We can help programmers to access and save data from different data sources like SQL Server, XML documents, collections, etc.

LINQ Syntax

Before we start performing operations using LINQ, we need to import the system.Linq namespace in our application.

We can perform LINQ operations in two ways:

  • LINQ query syntax
  • LINQ method syntax

LINQ Query Syntax

Using LINQ we can perform different querying operations using the query syntax. It is quite different from SQL and it requires us to follow the syntax hierarchy as shown below.

The hierarchy for the sentence is given in the following order.

From, in, let, where, order by, select, group by, into

These are the order hierarchy that needs to be maintained while writing the LINQ query syntax. Let’s have a look at the common syntax for LINQ query syntax.

Syntax

from variable_name in collection_name 
< where, grouping, operators > < lambda expressions> 
< select for groupBy operator> < format the results>

Let’s have a look at an example, to understand the usage of query syntax more clearly.

Program

        public static void Main(string[] args)
        {

            int[] ar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

            var query = from num in ar
                        where num < 3
                        select num;
            foreach (var v in query)
            {
                Console.WriteLine(v);
            }

        }

Output

1
2

Explanation

In this example, we defined an integer type array with some test data. Then we used a var type variable to store the result of the LINQ query. Later we used a foreach loop to print all the content of the result.

The above example shows us how to use the LINQ query syntax in our program.

LINQ Method Syntax

The method syntax uses the extension method of the Enumerable class. Method Syntax is quite different from query syntax.

Given below is an example to see how Method Syntax works.

Program

public static void Main(string[] args)
        {

            int[] ar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

            IEnumerable<int> query = ar.Where(n => n > 9).ToList();

            foreach (var v in query)
            {
                Console.WriteLine(v);
            }

        }

Output

10
11
12

Explanation

Here, have an integer type array with some integer data. Then we ran the method query on the integer array. We used a foreach loop to retrieve the data from the result of the query. This gives us the result based on the condition we provided in the method syntax.

Conclusion

We learned that LINQ is an integrated query language that was introduced into the .Net framework.

It offers a solution to query different data sources such as XML documents collections SQL databases etc. It can be used with both C Sharp and VB.net.

=> Check ALL C# Tutorials Here

Was this helpful?

Thanks for your feedback!

Leave a Comment