In the previous article, I mentioned how to Convert C# Class to JSON with Example but in this article, I have mentioned how we can set default value to a C# Class property with an example.
If we are using C# 6 or above, we can simply use the below code to set or give a value to the Auto Property
public class DefaultValue
{
public string FirstName { get; set; } = "John Wick"; // default value = john wick
}
So if we consider a complete Console application example, it would be as below
using System;
namespace DefaultCSharp
{
internal class Program
{
static void Main(string[] args)
{
DefaultValue obj = new DefaultValue();
Console.WriteLine(obj.FirstName);
}
}
public class DefaultValue
{
public string FirstName { get; set; } = "John Wick";
}
}
Output:
John Wick
Using DefaultValueAttribute
We can also use DefaultValueAttribute to property default value to a property, here is an example of using it
private string _val = "Last Name Here";
[DefaultValue(false)]
public string LastName
{
get
{
return _val;
}
set
{
_val = value;
}
}
So, if we consider complete console application example, it would be as below
using System;
using System.ComponentModel;
namespace DefaultCSharp
{
internal class Program
{
static void Main(string[] args)
{
DefaultValue obj = new DefaultValue();
Console.WriteLine(obj.LastName);
}
}
public class DefaultValue
{
private string _val = "Last Name Here";
[DefaultValue(false)]
public string LastName
{
get
{
return _val;
}
set
{
_val = value;
}
}
}
}
Output:
Last Name Here
Using Constructor (For below C# 6)
If you are using C# 5 or below version, then to set default value you will have to use Constructor
So for above example, it would go like this
public class DefaultValue
{
public DefaultValue()
{
FirstName = "John Wick";
}
public string FirstName { get; set; }
}
Complete C# example, would be as below
using System;
namespace DefaultCSharp
{
internal class Program
{
static void Main(string[] args)
{
DefaultValue obj = new DefaultValue();
Console.WriteLine(obj.FirstName);
}
}
public class DefaultValue
{
public DefaultValue()
{
FirstName = "John Wick";
}
public string FirstName { get; set; }
}
}
Output:
John Wick
That's it, hope it helps.
You may also like to read:
Get IP Address using C# (Local and Public IP Example)
Select vs SelectMany in C# With Example