Skip to content

Mustafa Ateş UZUN Blog

mustafauzun.co

  • About
  • Blog
  • Home
  • »
  • C#
  • »
  • C#, how to create your own variable type
  • »
    • September 16, 2022September 16, 2022
    • by mustafauzun
  • C#

C#, how to create your own variable type

Do you know that you can create your own variable types in C# programming language.

Here is a good example.
In this code, only 1 or 0 can be assigned to the variable.

(Source: My Gist)

struct BoolInt
{
    private readonly int value;
    private BoolInt(int value)
    {
        this.value = value;
    }

    private int Value
    {
        get { return value; }
    }

    public static implicit operator BoolInt(int value)
    {
        if (value > 1 || value < 0)
        {
            throw new Exception("Value can be only 1 or 0");
        }
        else
        {
            return new BoolInt(value);
        }
    }

    public static implicit operator int(BoolInt i)
    {
        return i.Value;
    }
}

Usage:

BoolInt val = 0;

BoolInt val2 = new BoolInt();
val2 = 1;
Tags: c#, struct, variable
Share

C#, turn the DataTable to string based calculator

C#, how to open an .exe in WinForm

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Javascript, Task Queue
  • Javascript, Thread Pool
  • Javascript, Lexical Environment
  • Javascript, Execution Context
  • Javascript, Event Delegation

Recent Comments

No comments to show.

Archives

  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • January 2022

Categories

  • C#
  • CMD
  • CSS
  • HTML
  • JavaScript
  • MongoDB
  • Node.js
  • Podcast
  • Powershell
  • Uncategorized
Theme: Puskar by Template Sell.