0% found this document useful (0 votes)
6 views8 pages

C# Basics: Data Types and Formatting

Uploaded by

hungnhth2209065
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

C# Basics: Data Types and Formatting

Uploaded by

hungnhth2209065
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PROGRAMMING IN C#

Module 1: Introduction to C# and VS 2017


Module 2: Variables and Data Types

Lab Guide for Lab1

Session Objectives
In this session, you will be practicing with
 Data type in C#
 Input and output data in C#
 Number and datetime format specifier
 Implicitly typed local variables
 Anonymous Types
Part 1 – Getting started (30 minutes)

Exercise 1
Step 1: Open Visual Studio 2008
Step 2: Select the menu File->New->Project to create console based project named ‘First_prg’ and
Solution named Session01 as shown in Figure 1

Figure 1: New Project Dialog Box


Step 3: Rename the class file ‘[Link]‘ to ‘First_prg.cs’
Step 4: Replace code in ‘First_prg.cs’ with given code
using System;
class Example
{
static void Main(string[] args)
{
[Link]("This is the my first program using C#”);
[Link]();
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build First_prg option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of the program as following

Exercise 2: Using datatype

Step 1: Add a console based project ‘DataType’ to the solution

Step 2: Right click on project DataTypes -> set as Startup project

2
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code

using System;
class Example
{
static void Main(string[] args)
{
int intVal;
double dblVal;
string strVal;
intVal = 10;
dblVal = 3.142;
strVal = "Fpt Aptech";
[Link]("{0} is an integer value", intVal);
[Link]("{0} is an double value", dblVal);
[Link]("{0} is an string", strVal);
[Link]();
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘DataTypes’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

Exercise 3: value type

Step 1: Add a console based project ‘ValueType’ to the solution


Step 2: Right click on project ValueType-> set as Startup project
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code

using System;
using [Link];

class Example1
{
static void Main(string[] args)
{
3
int valueVal = 5;
Test(valueVal);
[Link]("The value of the variable is {0}", valueVal);
[Link]();
}
static void Test(int valueVal)
{
int temp = 5;
valueVal = temp * 2;
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘ValueType’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

Exercise 3: Reference Type

Step 1: Add a console based project ‘ReferenceType’ to the solution


Step 2: Right click on project ReferenceType -> set as Startup project
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code

using System;
class ReferenceType
{
public int valueVal;
}
class TestReference
{
static void Main(string[] args)
{
ReferenceType refer = new ReferenceType();
[Link] = 5;
Test(refer);
[Link]("The value of the variable is {0}",
[Link]);
[Link]();
}
static void Test(ReferenceType refer)
4
{
int temp = 5;
[Link] = temp * 2;
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ReferenceType option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

Exercise 4: Number format specifier

Step 1: Add a console based project ‘NumberFormat’ to the solution


Step 2: Right click on project NumberFormat -> set as Startup project
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code

/*This program demonstrates the the numeric formatting in C#*/


using System;
class NumberFormat
{
static void Main(string[] args)
{
[Link]("Currency formatting - {0:C} {1:C4}", 88.8, 888.8);
[Link]("Integer formatting - {0:D5}", 88);
[Link]("Exponential formatting - {0:E}", 888.8);
[Link]("Fixed-point formatting - {0:F3}", 888.8888);
[Link]("General formatting - {0:G}", 888.8888);
[Link]("Number formatting - {0:N}", 8888888.8);
[Link]("Hexadecimal formatting - {0:X4}", 88);
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘NumberFormat’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
5
The output of program as following

Exercise 5: Datetime format specifier

Step 1: Add a console based project ‘DateTimeFormat’ to the solution


Step 2: Right click on project DateTimeFormat -> set as Startup project
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code

using System;
class MainClass
{
public static void Main()
{
DateTime dt = [Link]; // obtain current time

[Link]("d format: {0:d}", dt);


[Link]("D format: {0:D}", dt);

[Link]("t format: {0:t}", dt);


[Link]("T format: {0:T}", dt);

[Link]("f format: {0:f}", dt);


[Link]("F format: {0:F}", dt);

[Link]("g format: {0:g}", dt);


[Link]("G format: {0:G}", dt);

[Link]("m format: {0:m}", dt);


[Link]("M format: {0:M}", dt);

[Link]("r format: {0:r}", dt);


[Link]("R format: {0:R}", dt);

[Link]("s format: {0:s}", dt);

6
[Link]("u format: {0:u}", dt);
[Link]("U format: {0:U}", dt);

[Link]("y format: {0:y}", dt);


[Link]("Y format: {0:Y}", dt);
}
}

Step 5: Select menu File -> Save to save the file


Step 6: Select Build -> Build ‘DateTimeFormat’ option to build the project
Step 7: Select Debug -> Start without Debuging to execute the program
The output of program as following

Exercise 6: Implicitly typed local variables

Step 1: Add a console based project ‘ImplicitilyTypedLocal’ to the solution


Step 2: Right click on project ImplicitilyTypedLocal’ -> set as Startup project
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code
class ImplicitilyTypedLocal
{
static void Main(string[] args)
{
var i = 5;
var s = "hello";
var d = 1.0;
//i is an integer
[Link]("i*i: " +i * i);
//s is a string
[Link]("s in upper case:" + [Link]());
//d is a double
[Link]("type of d:" +[Link]());
[Link]();

}
7
}

Step 5: Run the program


Exercise 7: Anonymous Types variables
Step 1: Add a console based project ‘AnonTypes” to the solution
Step 2: Right click on project AnonTypes-> set as Startup project
Step 3: Rename the class file ‘[Link]’ to ‘[Link]’
Step 4: Replace the code in ‘[Link]’ with the given code
class AnonTypes
{
static void Main(string[] args)
{
var p1 = new { Name = "A", Price = 3 };
[Link]("Name = {0}\nPrice = {1}",
[Link](), [Link]);
[Link]();

}
}

Step 5: Run the program


Part 2 – Do it your self
Exercise 1: Write a program to enter: name, address, phone and display these information.
Exercise 2: Write a program to accept three integer number and find maximun number from three integer.
Exercise 3: Write a program that accepts a number between 1 and 7 from the user and return the
corresponding day of the week(1- Monday, 2- Tuesday and so on).
Exercise 4: Write a program to display the first 9 multiples of an integer. N entered from user

Exercise 5: Write a program to print the factorials of the integers from 1 to 20

Common questions

Powered by AI

In C#, variable mutability significantly affects program behavior, particularly when contrasting value and reference types. Value types (immutable in method context) result in unchanged variables after method calls, as seen with the 'ValueType' project where 'valueVal' remains unaffected by the 'Test' method. Conversely, reference types allow mutable behavior, where changes in method affect the original instance, as demonstrated by 'ReferenceType' project where 'refer.valueVal' is altered within 'Test'. Understanding this distinction is crucial for managing state changes and debugging .

Console applications offer simplicity, focus, and minimal overhead for learning programming basics, allowing learners to concentrate on logic without GUI complexity, as demonstrated in the exercises. They provide immediate feedback and enhance understanding of input/output processing. However, they might not adequately prepare learners for real-world application development, where GUI, networking, and database integration skills are necessary. The exercises leverage console applications to strengthen foundational programming concepts with high clarity .

Datetime format specifiers in C# use specific format strings to represent date and time in various formats. For example, 'd' produces a short date format, 'D' a long date format, 't' a short time, 'T' a long time, 'f' combines full date with short time, and so forth. Each format specifier provides a unique string representation suitable for different contexts, as shown in the 'DateTimeFormat' project where each specifier results in different representations of the current date and time .

Understanding data types benefits a C# programmer by enabling efficient data handling and manipulation, ensuring type safety, and optimizing memory usage. Exercises involving basic data types like 'int', 'double', and 'string' demonstrate their specific properties and use cases, reinforcing the importance of selecting appropriate types for different operations and enhancing the clarity and reliability of the code by preventing type errors .

The primary difference between value types and reference types is how they store data. Value types, demonstrated in the 'ValueType' project, directly contain their data. When passed to a method, a copy of the data is passed, meaning changes to the data within the method do not affect the original variable. In contrast, reference types, shown in the 'ReferenceType' project, store references to the actual data. When passed to a method, the reference is passed, allowing changes to the data within the method to affect the original variable .

C# handles implicit typing using the 'var' keyword, which allows the compiler to infer the type of a variable based on the value assigned to it. In 'ImplicitlyTypedLocal' project, variables such as 'i', 's', and 'd' are declared using 'var', and their types are deduced by their initialization (int, string, and double respectively). The advantages include cleaner code and reduced redundancy, while also allowing for dynamic handling of types as exemplified by the 'GetType' method confirming 'd' as a double .

Visual Studio plays a crucial role in the C# development workflow by providing an integrated environment for coding, building, and debugging applications. The exercises involve using Visual Studio to create new projects, build solutions, and execute code, offering features like syntax highlighting, debugging tools, and project management to enhance productivity and streamline the coding process .

C# supports customization of numerical and datetime outputs through format specifiers, allowing developers to precisely define how numbers and dates should appear. This is important for achieving consistency across different locales and domains, ensuring that outputs meet user expectations and application requirements, as demonstrated by 'NumberFormat' and 'DateTimeFormat' projects. Customization is critical for applications involving financial data or cross-cultural communication, where misinterpretation of formats could lead to errors or misunderstandings .

C# supports anonymous types to provide a way to encapsulate a set of read-only properties into a single object without explicitly defining a type. In the 'AnonTypes' project, an anonymous type is created with properties 'Name' and 'Price'. These types are useful for data transformations where a temporary structure to hold data is needed, as they simplify the code by avoiding explicitly defined classes for short-lived objects, enhancing flexibility and reducing boilerplate code .

Numeric format specifiers are used to control the appearance of numbers when converted to strings. The 'NumberFormat' project demonstrates various specifiers: 'C' for currency, 'D' for decimal integers, 'E' for exponential notation, 'F' for fixed-point, 'G' for general numeric formats, 'N' for number with thousands separators, and 'X' for hexadecimal. These specifiers are significant for presenting numbers consistently across applications, enabling more readable and culturally appropriate number formats, especially important for financial and scientific computing .

You might also like