What is the difference between String and string in C#? Which one to use?


I recently came across a client’s code base which made use of “String” and “string” keywords. The Client wanted to clean up code and make them all consistent (string). With over 8 million lines of code and 50 plus developers working on 12 different features within the same SVN branch. This was going to be a mission.

From investigation we concluded that the task was massive and gains were trivial. This code cleanup was unnecessary and could be done little bit at a time.

Basically, in C# “string” is alias to “String” class which lives in the System namespace.

So, is there any difference?

No. Not at all. You can use either.

What built in type aliases are there?

Microsoft has the following built in Alias types.

C# Types              .NET type
bool                       System.Boolean
byte                       System.Byte
sbyte                      System.SByte
char                       System.Char
decimal                 System.Decimal
double                   System.Double
float                       System.Single
int                          System.Int32
uint                        System.UInt32
long                       System.Int64
ulong                     System.UInt64
object                    System.Object
short                      System.Int16
ushort                    System.UInt16
string                     System.String

Why have built in types?

The main reason is for readability. 



Its more intuitive to read code with blue keywords as seen above. Whereas the classes are more less for static method invocation.








As you can see from code above. The “String” is dimmer and has a suggestion.

When you inspect the suggestion in Visual Studio. You can see that suggestion is to simplify the name to lower case (string).

Summary.

  1. String or string does not matter.
  2. If you writing new code then better to follow Microsoft suggestions and go with built in aliases. Unless your company has a different standard.
  3. Don’t waste time in clean-ups.

MVC C# Converting string to int

Here is an example for converting string to int in c#.


You can use System.Convert library to convert this.

 private static string myString = "123";
 private int id = Convert.ToInt32(myString);


Or, you can use System.Int32
 private string myString = "123";
 private int id = Int32.Parse(myString);


If your string is not numeric then it will throw an exception. In that case you can use the following.           
  private static string myString = "123";
 private static int convertedValue;
 private bool success = Int32.TryParse(myString, out convertedValue);



Here success will determine if your string was converted successfully or not. The convertedValue will contain the converted string value if its successful, otherwise contain its initialized value.  

How to implement an age display helper in C#

Here is a snippet for formatting age display. You can expand on this helper to suit your needs.
I implemented this helper for a client wanted to hide the age of users who were younger than 14 years.

public static string AgeDisplay(this HtmlHelper helper, DateTime birthday) {
    var now = DateTime.Today;
    var age = now.Year - birthday.Year;
    var result = "";
    if (now < birthday.AddYears(age)) age--;
    if (age >= 14)   // Dont display age, of any users who are younger then 14 years old.
    {
        result = age + "years old, ";
    }
    return result;
}


MVC C# SQL Membership Provider How to get User Name of Logged in User

Finding the User Name of the currency logged on user or any user is very simple.

You can use System.Web.Security.Membership namespace.

To find the user name of the current logged in user.

var username = User.Identity.Name;

Further more you can get all membership details of any registered member by

var username = User.Identity.Name;
var membershipUser = Membership.GetUser(username);// pass in the username of the user whose membership details you want to access.

Now to access the Guid of the user you can do this.

if (membershipUser != null){
var userGuid = (Guid)membershipUser.ProviderUserKey;
}

Software development tools and tips

Here are some software development tools and tips that can be helpful for developers.


Tools


MS Visual Studio - A top notch programming IDE that most developers and development firms use. Ultimate version is quite expensive. There is a free version Visual Studio Express. Also students can get free copy from Microsoft's Student Partner program.

MS SQL Server Express - Free database development tool by Microsoft

ReSharper -  A tool that when installed integrates with Visual Studio and provides you with hints for improving code, refactoring and identifying errors easily by highlighting them. This is highly recommended tool It can be a bit expensive to purchase. But there is a free trial available.

Bootstrap - Helps to quickly get your website CSS'ed. It had predefined classes, icons and scripts that can cut your development time.

JQuery - An open source, cross-browser collection of scripts that provide quick client side scripting of webpages. There are some premium plugins as well.

SVN - An open source version control. Creates copies of work committed by development team. Allows merging of code and reverting if to a specific version if need.


Some tips:


1. Dual monitors - Having 2 monitors is very common for developers. It provides more viewing space and helps reduce time spent on resizing and flipping between windows.

2. Skype, Lync or Team Viewer - Collaboration tools that helps your communicate, see  and even control other team members computer.

3. Take care of yourself - As a Developer you spend lots of time sitting in-front of your computer coding. Make a rule to get up and stretch or take a short walk every hour. Its sometimes nice to stand and code. You can try having a small stand that can help raise your keyboard and monitor.

4. Networking - Try to build a network or join a network of developers. This way you can gain more knowledge and make some friends.


MVC C# How to implement a dropdown list

To implement a dropdown list. Its most preferable to do so in the controller action method. Firstly you will need to create a List of SelectListItem. SelectListItem belongs to the System.Web.Mvc Here i have a brand select list. Which will allow me to choose which brand of phone i want to purchase.
var brandsList = new List<SelectListItem>(){
    new SelectListItem() { Text = "None", Value = "0" },
    new SelectListItem() { Text = "Samsung", Value = "1" },
    new SelectListItem() { Text = "Apple", Value = "2" },
    new SelectListItem() { Text = "Microsoft", Value = "3" }
};
This is a phone class which i will be rendering a MVC razor view for.
public class Phone
{
    public int Brand { get; set; }

    public decimal Cost { get; set; }

    public List<selectlistitem> BrandsList { get; set; }
}
Here, i am creating an "Create" action in my PhoneController. In this i am assigning my brand list of items to the Phone models BrandList.
public ActionResult Create() {
    var phone = new Phone();

    var brandsList = new List<SelectListItem>(){
                new SelectListItem() { Text = "None", Value = "0" },
                new SelectListItem() { Text = "Samsung", Value = "1" },
                new SelectListItem() { Text = "Apple", Value = "2" },
                new SelectListItem() { Text = "Microsoft", Value = "3" }
            };

    phone.BrandsList = brandsList;

    return View(phone);
}

Finally in my razor view i have a drowdownlistfor template with the first parameter as Brand property and the second parameter is the BrandList. @Html.DropDownListFor(model => model.Brand, Model.BrandsList) The view rendered shows this...

The dropdown options shown are...

This is what gets rendered in HTML.

ASP.NET SQL Membership Provider (How to get the GUID of current user?)

Here is an example showing how you can get the GUID of the current logged in user in a controller using C#.


Step 1:

Firstly in your controller you need to include the namespace System.Web.Security.

Example:
using System.Web.Security;

You need this namespace because we will be using the Membership class to get the Membership information of the current logged in user. The Membership class resides within the System.Web.Security namespace.


Step 2:

This step shows a simple way, how you can retrieve the GUID of the current logged in user.

In your controller you can simply declare a variable to store the MembershipUser (shown in example below) by calling the Membership.GetUser(string method) method. We need to use User.Identity.Name property to get the username of the the current user and then input this username into the GetUser method.

Example:  GetUser(User.Identity.Name). The User.Identity.Name is under  System.Security.Principal
namespace.

Step 3:

So, now you will have something like var membershipUser = Membership.GetUser(User.Identity.Name).
This will get you the MembershipUser class object. This basically lets you access and update the user's membership information stored in the Membership data storage. You can then access the ProviderUserKey property, which will give you an object of GUID (this GUID is stored in SQL database as uniqueidentifier).

Example: var userGuid = membershipUser.ProviderUserKey;


Final step:

Finally you need to cast the object to GUID in order to be able to use the user's GUID.

Example: (Guid)userGuid.

If you do casting like this:  var userGuid = (Guid)membershipUser.ProviderUserKey; then it is risky because if the membershipUser is null or not present in the database, then a null reference error will occur. So you need to cast GUID when you are actually using the variable.


Working example:

This code shows a basic example. In this example you can cast the MembershipUser.ProviderUserKey to GUID straightaway, because we are using conditional statements to check that the membership user and the provider key is not null


    public ActionResult Index() {
        var membershipUser = Membership.GetUser(User.Identity.Name); //Get the  membership info
        if (membershipUser != null)//Check if user information is not null
        {
            if (membershipUser.ProviderUserKey != null)//Check if provider key is available
            {
                var userGuid = (Guid)membershipUser.ProviderUserKey; //Get key and cast to GUID
            }
        }
        return View();
    }

A more advance example. 

This example shows how you can check if the current logged in user has an existing profile in your website, and return the view containing the profile model.

Assuming that you have a Profile table in your website database and the primary key of the Profile table is UserGuid as uniqueidentifier. Also, assuming that you have a query called GetProfile(GUID userGuid) implemented in the ProfileRepository class, that returns the profile of the user with the particular GUID.

    [Authorize]
    public ActionResult Index() {
        var membershipUser = Membership.GetUser(User.Identity.Name);
        if (membershipUser != null) {
            if (membershipUser.ProviderUserKey != null) {
                var profile = _profile.GetProfile((Guid)membershipUser.ProviderUserKey);
                return View(profile);
            }
        }
        return View("Error");
    }
    


Hope this helps :) our fellow beginners to grasp some basic understanding of using ASP.NET Membership.