C# Numeric Data Type

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Numeric Datatype Method and Properties:

ToString(): Converts an integer to its string representation.

Example

int number = 42;

string numberAsString = number.ToString(); // “42”

Parse(): Converts a string containing an integer to an actual integer.

Example

string numberAsString = “123”;

int parsedNumber = int.Parse(numberAsString); // 123

Math Operations: You can perform various mathematical operations like addition, subtraction, multiplication, and division using standard operators like +, -, *, and /.

Example

int result = 10 + 5; // Addition

int difference = 20 – 8; // Subtraction

int product = 6 * 4; // Multiplication

int quotient = 16 / 2; // Division

Properties

MaxValue: Gets the maximum value that can be held by an integer of that type.

Example

int max = int.MaxValue; // 2147483647

MinValue: Gets the minimum value that can be held by an integer of that type

Example

int min = int.MinValue; // -2147483648

Size: Returns the number of bytes used to store the integer.

Example

int size = sizeof(int); // 4 bytes

These are some of the commonly used methods and properties when working with integer types in C#. They allow you to perform operations on integers and retrieve information about their limits and size.

C# int.Parse Vs int.TryParse Method

  • Convert a string representation of number to an integer,using the int.TryParse and intParse method in C#.

static void Main() {

      int res;

      string myStr = “120”;

      res = int.Parse(myStr);

      Console.WriteLine(“String is a numeric representation: “+res);

   }

static void Main() {

      bool res;

      int a;

      string myStr = “120”;

      res = int.TryParse(myStr, out a);

      Console.WriteLine(“String is a numeric representation: “+res);

   }

Output

String is a numeric representation: 120

Output

String is a numeric representation: True

If the string cannot be converted, then the int.TryParse method returns false i.e. a Boolean

  • value, whereas int.Parse returns an exception.

Programs To Practice

  • Practice variable declaration and initialization.
  • C# Program to find the minimum value and maximum value of All integer data types.
  • Practice Printing message on console using Interpolation, Concatenation and Place holder.
  • Practice the Method and properties of Integer, byte, short, long data types.