Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, 30 June 2015

STRINGS CHECK (EMPTYORNULL) IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIV WIRE  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 
To read STRINGS (NULLOREMPTY) IN C# - Click here.


CHECK BLANK STRING

A blank string is a type of string which contains nothing. Nothing means not even a single character and whose length is zero.



Let's just understand this by an example.

Example- There is a simple user input program. In which the system ask user to input his name. And then it prints the name to the output screen.

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class StringCheckNullEmpty
    {
        public static void Main()
        {

            Console.WriteLine("Enter You name");
            string name = Console.ReadLine();

            Console.WriteLine("Your name is = {0}.", name);

         }
    }
}


Output




Click imaginationhunt.blogspot to see latest Blogs
 
Hence, we get the output as expected.


But, suppose there is a user who didn't want to enter his name or leave it blank. And press Enter. Now, it's not correct to print the command like this- "Your name is = ."
So, to handle such situation, we check whether user has input some data string or not. And if not then we will alert it by saying "You have not entered your name". But the question arises how to do that?

4 Ways to Check String Null or Empty

Method1: Using "" (double quotes)

Blank string can be checked as str == "". "" (Double quotes) is the way to check blank string. Its return type is bool (i.e. true or false). Blank string only works when the length of string is zero.
Now, if user input an empty string, we would easily handle that by giving a message "You have not entered your name.".

Practical Implementation:

Click imaginationhunt.blogspot to see latest Blogs
 
using System;

namespace AspnetSolutions
{
    class StringCheckNullEmpty
    {
        public static void Main()
        {

            Console.WriteLine("Enter You name");
            string name = Console.ReadLine();

            if (name == "")
            {
                Console.WriteLine("Checking by blank string");
                Console.WriteLine("Length is = {0}",name.Length);
                Console.WriteLine("You have not entered your name.");
            }
            else
            {
                Console.WriteLine("Your name is = {0}.", name);
            }

         }
    }
}


Output


Here, we have placed an if-else block to check the condition. As the user left the name blank by pressing Enter. He automatically gets the alert "You have not entered your name." which we have placed in the overload of WriteLine() method.

Drawbacks:

1. This method will not work when string is null.
2. This method will not work for whitespaces. Implies if we give two spaces then this will not check empty string rather it may consider them as 2 characters. 


Click imaginationhunt.blogspot to see latest Blogs


Practical Implementation:

using System;

namespace AspnetSolutions
{
    class StringCheckNullEmpty
    {
        public static void Main()
        {

            // Checking when string is null
            string g = null;          
            Console.WriteLine(g == "");  // o/p is false


            // Checking when string has white spaces
            string h = "  ";
            Console.WriteLine(h == "");  // o/p is false

         }
    }
}


Output



As you can see the output for both null and white spaces string is False. Which means the double quotes check string does not work in these two cases.

To read STRINGS CHECK (EMPTYORNULL) IN C# part2 - Click here.

Related Questions:
Q-1 Which of the following option will be correct?
string email1="";
string email2=string.Empty;
string email3=null;

 

A) if (email1==email2)
    {
         Console.WriteLine("condition 1 is correct");
    }

B) if (email2 == email3)
    {
        Console.WriteLine("condition 2 is correct");
    }

C) if (email3 == email1)
    {
        Console.WriteLine("condition 3 is correct");
    }


Ans- Option(A).

Q-2 Which is the correct output for the piece of code?
string email2=string.Empty;
if (email2 != "")
{
    Console.WriteLine("condition successfully run");
}


Click imaginationhunt.blogspot to see latest Blogs

A) Code run. But print nothing.
B) condition successfully run
C) Compiler Error.
Ans- Option(A).

Keep learning and sharing...

Monday, 29 June 2015

STRINGS (NULLOREMPTY) IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIV WIRE  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 
How many ways are there in which we can make our string null or empty?




4 Ways:- Making string Null and Empty

1. Using ""(Double Quotes)
Double Quotes are the way in which we make our string holding zero characters. Its length is zero.
For ex- string str = "";

2. Using "   "(White Spaces)
White spaces are the way in which we make our string storing some data but actually they are blank spaces. They possess some length but in real they contain only blank spaces.

3. Using String.Empty
An empty string means a string that contains zero characters, whose length is zero. It is an instance of System.String object.

Click imaginationhunt.blogspot to see latest Blogs

4. Using NULL
"null" is also used to make empty string. But it is not an instance of System.String object. 
Note:
We cannot directly use null declared variables on method, as it may give NULLREFERENCEEXCEPTION. But what we can do is we can use the null declared variables with some other variables and do various operations.

Let's see each one of them

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class StringNullEmpty
    {
        public static void Main()
        {
            string abc = "";  // using double quotes
            string def = "  ";  //using whitespaces
            string pqr = string.Empty;  // using String.Empty
            string xyz = null;  //using null
              
            // Section-1 (
using double quotes)
            Console.WriteLine("using double quotes");
            Console.WriteLine(abc);
            Console.WriteLine("Length = {0}",abc.Length);
            Console.WriteLine("----------------");

            // Section-2 (using whitespaces)
            Console.WriteLine("using whitespaces");
            Console.WriteLine(def);
            Console.WriteLine("Length = {0}", def.Length);
            Console.WriteLine("----------------");

            // Section-3 (using String.Empty)
            Console.WriteLine("using String.Empty");
            Console.WriteLine(pqr);
            Console.WriteLine("Length = {0}", pqr.Length);
            Console.WriteLine("----------------");

            // Section-4 (using null)
            Console.WriteLine("using null");
            Console.WriteLine(xyz);
            try
            {
                Console.WriteLine("Length = {0}", xyz.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

        }
    }
}

Click imaginationhunt.blogspot to see latest Blogs

Output


As you can see we have shown all the 4 ways separately in 4 sections. By 3 different overloads of WriteLine() method
1. In first overload, we print the section (null, empty,etc) name.
2. In second, we directly print the variable.
3. And in last, we are calculating the size taken by the variable.

One thing that makes the program look weird is- we have use the try-catch block in the last statement when we are calculating the length of the 'null' declared variable 'xyz'. Why?
Because as we said we cannot directly use null declared variables, as it may give NULLREFERENCEEXCEPTION.


Click imaginationhunt.blogspot to see latest Blogs

But then question arises how to use null declared variables? Answer is - we can use with some other variables. 
Let's see this 

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class StringNullEmpty
    {
        public static void Main()
        {
            string def = "  ";  //using whitespaces
            string xyz = null;  //using null    

            string lmn = def + "," + xyz;
            Console.WriteLine(lmn);
            Console.WriteLine("Length = {0}",lmn.Length);

        }
    }
}

Output


By using with some other variable, null declared variable work efficiently with method and properties without throwing error.


Related questions:


Q-1 Which one is the correct method to delete white spaces from string?
A) Trim()
B) Remove()
C) Replace()
D) None of the above
Ans- Option(A).
Explanation- Let's understand by an example
Console.WriteLine("   Gopal  ".Trim());
O/p- Gopal

Q-2 What would be the length if a null declared string is added with a normal string? (Given- Length is 28)

using System;

namespace AspnetSolutions
{
    class StringNullEmpty
    {
        public static void Main()
        {
            string name = "Imaginationhunt.blogspot.com"; //  Given- Length is 28) 
            string lastname = null;

            name=name+lastname; 
            Console.WriteLine(name.Length); 
// Guess the Length ???
        }
    }
}
A) NullReferenceException
B) 28
Ans- Option(B).
Explanation: By using with some other variable (i.e. name), null declared variable (i.e. lastname) work efficiently with method and properties without throwing error.

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Sunday, 28 June 2015

IS STRING MUTABLE OR IMMUTABLE IN .NET?

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIV WIRE  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

What does Mutable means?

Mutable: Mutable means whose state can be changed after it is created. In simple terms to remind and understand the term you can relate it by word "Mutants". For ex- In X-Men, Jennifer Lawrence has the power to change itself from Mutant to Human being and back to mutant.




What does Immutable means?

Immutable: Immutable means whose state cannot be changed once it is created. For ex- A human being cannot change its state. He can wear a different type costume to look different but that doesn't mean his state has been changed.

Well, we are very much clear about the differences between these two terms.  
Now, put our focus on iterating whether strings are mutable or immutable?
Let's check it out...

Click imaginationhunt.blogspot to see latest Blogs

Example- Let's take a string and apply some operation on it. That would give us a conclusion whether strings are mutable or immutable.

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class StringImmutableNotMutable
    {
        public static void Main()
        {
          string rootStr = "Imaginationhunt.blogspot";

          // Operations(O)
          string manipulateStr = rootStr.Replace('o', 'a')// O1. Applying Replace()

          // Results(R)
          Console.WriteLine("Original String = " + rootStr);  //R1. "rootStr" Before operation
          Console.WriteLine("Using Replace()= " + manipulateStr); //R2. replacing performed
          Console.WriteLine("Original String = " + rootStr);  //R3. ''rootStr" After operation

          // Operations(O)
          string concatenateStr = rootStr + ".com";           // O2. Applying Concatenation
           

          // Results(R)
          Console.WriteLine("After Concatenate = " + concatenateStr);//R4. concat performed
          Console.WriteLine("Original String = " + rootStr);//R5. "rootStr" After concatenation
        }
    }
}

Output


(Refer O1, O2, R1, R2, R3, R4, R5 from above code.)
Let's understand output of the code in Steps:

Click imaginationhunt.blogspot to see latest Blogs

Step1: We initialize and declare a string "rootStr" as "Imaginationhunt.blogspot".

Step2: We apply some operation on string "rootStr".

Operation (O1)- Here, we are using the String.Replace() method to replace the old character 'o' by new character 'a'. And storing the output in string variable "manipulateStr". Why we are storing it in string data type? Because the return type of String.Replace() method is String.

Operation (O2)- Here, we are using the '+' sign to concatenate/join the "rootStr" with a hard coded string literal ".com". And storing the output in string variable "concatenateStr". Because the root string and the string literal both are in string type so, the type is string.  

Step3: Now, we first print the original string "rootStr", which give us -> "Imaginationhunt.blogspot" see (R1).

Step4: We now print the result for "manipulateStr", which give us -> "Imaginatianhunt.blagspat" see (R2). As we can see the Replace() method is performing on "rootStr", which means the string now has been changed.

Click imaginationhunt.blogspot to see latest Blogs

Step5: Let just pass the string "rootStr" to overload of WriteLine() to see whether it's showing the original string "rootStr" (i.e. "Imaginationhunt.blogspot") or the "manipulateStr" (i.e. "Imaginatianhunt.blagspat") see (R3). And what we got as result, the "rootStr", which means whatever operation we may perform on "rootStr". At the end we are always getting our original string, which is our root string. This shows the immutable nature of string.

Step6: Let's perform another operation on "rootStr" to make it more clear and understandable. This time we concatenate our original string with string literal ".com" see (O2).

Step7: Now, printing the string "concatenateStr" see (R4). Returns a new string instance instead of changing the old one.

Step8: And finally, printing again the "rootStr". And it gives us the exact string as the original string see (R5).

Therefore, from both the operation that we perform on string and getting back our original string shows the immutable nature of string
Hence, we concluded that the strings in .Net are immutable.


To read STRINGS (NULL AND EMPTY) IN C# - Click here.


Related Questions:

#newtoprgm try firstprogram

Q-1 What does the term 'immutable' means in terms of string objects?
A) We can modify characters included in the string
B) We cannot perform various operation of comparison, inserting, appending, etc.
C) We cannot modify characters contained in the string.
D) None of the mentioned
Ans- Option (C).
Explanation- String objects are 'immutable' it means we cannot modify the characters contained in string also operation on string produce a modified version rather than modifying characters of string.

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Saturday, 27 June 2015

STRING.LENGTH PROPERTY IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIV WIRE  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 


String.Length

 
Length is used to get the number of character used in the specified string from the given string. Its return type is Integer. Length property always implemented as String.Length.

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class StringLength
    {
        public static void Main()
        {
            string str = "Name=Tapan,Education=BCA,Mb=xxxxxxx,Email=Tap@tap.com";
            Console.WriteLine("Length");
            //Using Length
            Console.WriteLine("Using String: " + str.Length);
            Console.WriteLine("Using Substring: " + str.Substring(str.LastIndexOf("T")).Length);
        }
    }
}


Output

FIGURE 1


Click imaginationhunt.blogspot to see latest Blogs

In the output window, we have two different outcomes. Let's understand each one of them.
a) Using String- In first we learn how to get the length of string. We have done this by using the Length property across the string 'str'. The output that we get is the total characters used in the string i.e. 53, which means there are 53 characters used in the string 'str'.
b) Using Substring- Second one shows how we can get a sub part of the given string using substring() method and then find the length of the substring. For ex- fetching out 'Tap@tap.com' and then using the Length property across the substring will give the number of character used in the string. Hence, as result we get 11, which means there are 11 characters used in the substring.

Real time example of using Length:

Suppose your task is to build user input program in which user has to input a password. And the maximum length of the password is 10 characters.

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class
StringLength 
    {
        public static void Main(string[] args)
        {

            Console.WriteLine("Enter your password - Max size 10 digit");
            string password = Console.ReadLine();
            int passwordlength = password.Length;
            if (passwordlength <= 10)
            {
                Console.WriteLine("Password saved.");
            }
            else
            {
                Console.WriteLine("Password length should be 10 digit max");

            }
         }
    }
}

 

Click imaginationhunt.blogspot to see latest Blogs

Output


FIGURE 2
Figure 2 shows the outcome when password length is within limit.

FIGURE 3
Figure 3 shows the outcome when password length is exceeding limit.

To read IS STRING MUTABLE OR IMMUTABLE IN .NET? - Click here.

Related Question:

#newtoprgm try firstprogram

Q-1 What will be the output of the code?

using System;

namespace AspnetSolutions
{
    class
StringLength
     {
        public static void Main(string[] args)
        {

           string emptyStr = "";
           string emptyStr3 = "\0";

           Console.WriteLine("Strpassed = {0} and Length = {1}", emptyStr, emptyStr.Length);
           Console.WriteLine("Strpassed = {0} and Length = {1}", emptyStr3, emptyStr3.Length);

        }
    }
}


A) 0,0
B) 0,1
C) 1,0
D) 1,1
Ans- Option(B).

Click imaginationhunt.blogspot to see latest Blogs

Q-2 What will be the output of the code?


using System;

namespace AspnetSolutions
{
    class
StringLength
     {
        public static void Main(string[] args)
        {

             Console.WriteLine("Imaginationhunt.blogspot".Length);
        }
    }
}

A) 23
B) 24
C) 0
D) 1
E) Error
Ans- Option(B).
Explanation- Yes, the statement is correct. Literals can be declared like this.

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Featured post

Think that makes you rich and richer

 Napolean said: “You can think and grow rich, but if you can be brought up like most people with work and you won't starve, this wil...