Get the App
SLTechnology News&Howtos  ›  Development  › 

How to define constant in C #

Shulou Source: shulou.com Published: 2022-06-01 02:09:11 09月10日 Update

This article mainly explains "how to define constants in C#". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to define constants in C#"!

define constants

Constants are defined using the const keyword. The syntax for defining a constant is as follows:

const = value;

The following code demonstrates how to define and use constants in a program:

examples

using System;

public class ConstTest

{

class SampleClass

{

public int x;

public int y;

public const int c1 = 5;

public const int c2 = c1 + 5;

public SampleClass(int p1, int p2)

{

x = p1;

y = p2;

}

}

static void Main()

{

SampleClass mC = new SampleClass(11, 22);

Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);

Console.WriteLine("c1 = {0}, c2 = {1}",

SampleClass.c1, SampleClass.c2);

}

}

When the above code is compiled and executed, it produces the following results:

x = 11, y = 22c1 = 5, c2 = 10 At this point, I believe that everyone has a deeper understanding of "how to define constants in C#", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Constants codes content facets learning practicality deeper keywords interests examples practicality practicality simplicity of operation methods more friends programs results Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Xiaomi Microsoft vpn MariaDB