C# Tutorial for Frontend Developer
1.Basic
Hello World
Console output -> console.log
Console.WriteLine("Hello World!");
Variable declaration and value assignment
string aFriend = "Bill";
Console.WriteLine(aFriend);
aFriend = "Maira";
Console.WriteLine(aFriend);
String joining with '+' (not recommended in project)
// work, but bad
Console.WriteLine("Hello " + aFriend);
// work as good, String interpolation
Console.WriteLine($"Hello {aFriend}");
string firstFriend = "Maria";
string secondFriend = "Sage";
Console.WriteLine($"My friends are {firstFriend} and {secondFriend}");
// work with properties
Console.WriteLine($"The name {firstFriend} has {firstFriend.Length} letters."); Console.WriteLine($"The name {secondFriend} has {secondFriend.Length} letters.");
Trim
, TrimStart
, TrimEnd
string greeting = " Hello World! ";
Console.WriteLine($"[{greeting}]");
string trimmedGreeting = greeting.TrimStart();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.TrimEnd();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.Trim();
Console.WriteLine($"[{trimmedGreeting}]");
Replace
string sayHello = "Hello World!";
Console.WriteLine(sayHello);
sayHello = sayHello.Replace("Hello", "Greetings");
Console.WriteLine(sayHello);
ToUpper
, ToLower
Console.WriteLine(sayHello.ToUpper());
Console.WriteLine(sayHello.ToLower());
Contains
string songLyrics = "You say goodbye, and I say hello"; Console.WriteLine(songLyrics.Contains("goodbye")); Console.WriteLine(songLyrics.Contains("greetings"));
StartsWith
and EndsWith
string songLyrics = "You say goodbye, and I say hello"; Console.WriteLine(songLyrics.StartsWith("You")); Console.WriteLine(songLyrics.StartsWith("goodbye")); Console.WriteLine(songLyrics.EndsWith("hello")); Console.WriteLine(songLyrics.EndsWith("goodbye"));
Numbers in C#
int a = 18;
int b = 6;
int c = a + b;
Console.WriteLine(c);
int
as integer-
for subtraction*
for multiplication/
for division
Subtraction
int c = a - b;
Multiplication
int c = a * b;
Division
int c = a / b;
Multiplication and division take precedence over addition and subtraction.
int a = 5;
int b = 4;
int c = 2;
int d = a + b * c;
Console.WriteLine(d);
You can force a different order of operation by adding parentheses around the operation or operations you want performed first:
int a = 5;
int b = 4;
int c = 2;
int d = (a + b) * c;
Console.WriteLine(d);
Replace the fourth line above with something like this:
int d = (a + b) - 6 * c + (12 * 4) / 3 + 12;
Integer division always produces an integer result, even when you'd expect the result to include a decimal or fractional portion.
int a = 7;
int b = 4;
int c = 3;
int d = (a + b) / c;
Console.WriteLine(d);
That last sample showed you that integer division truncates the result. You can get the remainder by using the remainder operator, the % character:
int a = 7;
int b = 4;
int c = 3;
int d = (a + b) / c;
int e = (a + b) % c;
Console.WriteLine($"quotient: {d}");
Console.WriteLine($"remainder: {e}");
int max = int.MaxValue;
int min = int.MinValue;
Console.WriteLine($"The range of integers is {min} to {max}");
If a calculation produces a value that exceeds those limits, you have an underflow or overflow condition.
int what = max + 3;
Console.WriteLine($"An example of overflow: {what}");
Work with the double type
The double
numeric type represents a double-precision floating point number. Those terms may be new to you. A floating point number is useful to represent non-integral numbers that may be very large or small in magnitude. Double-precision is a relative term that describes the numbers of binary digits used to store the value. Double precision number have twice the number of binary digits as single-precision. On modern computers, it is more common to use double precision than single precision numbers. Single precision numbers are declared using the float
keyword. Let's explore. Try the following code in the interactive window and see the result:
double a = 5;
double b = 4;
double c = 2;
double d = (a + b) / c;
Console.WriteLine(d);
Notice that the answer includes the decimal portion of the quotient. Try a slightly more complicated expression with doubles:
double a = 19;
double b = 23;
double c = 8;
double d = (a + b) / c;
Console.WriteLine(d);
double max = double.MaxValue;
double min = double.MinValue;
Console.WriteLine($"The range of double is {min} to {max}");
These values are printed out in scientific notation. The number to the left of the E
is the significand. The number to the right is the exponent, as a power of 10.Just like decimal numbers in math, doubles in C# can have rounding errors. Try this code:
double third = 1.0 / 3.0;
Console.WriteLine(third);
Work with decimal types
You've seen the basic numeric types in C#: integers and doubles. There's one other type to learn: the decimal
type. The decimal type has a smaller range but greater precision than double
. Let's take a look:
decimal min = decimal.MinValue;
decimal max = decimal.MaxValue;
Console.WriteLine($"The range of the decimal type is {min} to {max}");
Notice that the range is smaller than the double type. You can see the greater precision with the decimal type by trying the following code:
double a = 1.0;
double b = 3.0;
Console.WriteLine(a / b);
decimal c = 1.0M;
decimal d = 3.0M;
Console.WriteLine(c / d);
The M
suffix on the numbers is how you indicate that a constant should use the decimal
type.Notice that the math using the decimal type has more digits to the right of the decimal point.
The M
suffix on the numbers is how you indicate that a constant should use the decimal
type. Otherwise, the compiler assumes the double
type.
ChallengeNow that you've seen the different numeric types, write code that calculates the area of a circle whose radius is 2.50 centimeters. Remember that the area of a circle is the radius squared multiplied by PI. One hint: .NET contains a constant for PI, Math.PI that you can use for that value. Math.PI, like all constants declared in the System.Math namespace, is a double value. For that reason, you should use double instead of decimal values for this challenge.You should get an answer between 19 and 20.
double radius = 2.50;
double area = Math.PI * radius * radius;
Console.WriteLine(area);
Logic with Branch and Loop statements
int a = 5;
int b = 6;
if (a + b > 10)
Console.WriteLine("The answer is greater than 10.");
Modify the declaration of b so that the sum is less than 10:
int b = 3;
Select the Run button again. Because the answer is less than 10, nothing is printed. The condition you're testing is false. You don't have any code to execute because you've only written one of the possible branches for an if statement: the true branch.
Tip
As you explore C# (or any programming language), you'll make mistakes when you write code. The compiler will find those errors and report them to you. When the output contains error messages, look closely at the example code, and the code in the interactive window to see what to fix. That exercise will help you learn the structure of C# code.
This first sample shows the power of if and boolean types. A boolean is a variable that can have one of two values: true or false. C# defines a special type, bool for boolean variables. The if statement checks the value of a bool. When the value is true, the statement following the if executes. Otherwise, it's skipped.This process of checking conditions and executing statements based on those conditions is powerful. Let's explore more.
To execute different code in both the true and false branches, you create an else branch that executes when the condition is false. Try this:
int a = 5;
int b = 3;
if (a + b > 10)
Console.WriteLine("The answer is greater than 10");
else
Console.WriteLine("The answer is not greater than 10");
int a = 5;
int b = 3;
if (a + b > 10)
{
Console.WriteLine("The answer is greater than 10");
}
else
{
Console.WriteLine("The answer is not greater than 10");
}
int a = 5;
int b = 3;
int c = 4;
if ((a + b + c > 10) && (a == b))
{
Console.WriteLine("The answer is greater than 10");
Console.WriteLine("And the first number is equal to the second");
}
else
{
Console.WriteLine("The answer is not greater than 10");
Console.WriteLine("Or the first number is not equal to the second");
}
The && represents "and". It means both conditions must be true to execute the statement in the true branch. These examples also show that you can have multiple statements in each conditional branch, provided you enclose them in { and }.
int a = 5;
int b = 3;
int c = 4;
if ((a + b + c > 10) || (a == b))
{
Console.WriteLine("The answer is greater than 10");
Console.WriteLine("Or the first number is equal to the second");
}
else
{
Console.WriteLine("The answer is not greater than 10");
Console.WriteLine("And the first number is not equal to the second");
}
Modify the values of a, b, and c and switch between && and || to explore. You'll gain more understanding of how the && and || operators work.
Use loops to repeat operations
int counter = 0;
while (counter < 10)
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
}
The while
statement checks a condition and executes the statement following the while
. It will repeat checking the condition and executing those statements until the condition is false.There's one other new operator in this example. The ++
after the counter
variable is the increment operator. It adds 1 to the value of counter, and stores that value in the counter variable.
Make sure that the while loop condition does switch to false as you execute the code. Otherwise, you create an infinite loop where your program never ends. Let's not demonstrate that, because the engine that runs your code will time out and you'll see no output from your program.
The while
loop tests the condition before executing the code following the while
. The do ... while
loop executes the code first, and then checks the condition. It looks like this:
int counter = 0;
do
{
Console.WriteLine($"Hello World! The counter is {counter}");
counter++;
} while (counter < 10);
Work with the for loop
for(int counter = 0; counter < 10; counter++)
{
Console.WriteLine($"Hello World! The counter is {counter}");
}
The for
statement has three parts that control how it works.
The first part is the for initializer: int counter = 0;
declares that counter is the loop variable, and sets its initial value to 0
.
The middle part is the for condition: counter < 10
declares that this for loop continues to execute as long as the value of counter is less than 10.
The final part is the for iterator: counter++
specifies how to modify the loop variable after executing the block following the for statement. Here, it specifies that counter should be incremented by 1 each time the block executes.
Experiment with these yourself. Try each of the following:
- Change the initializer to start at a different value.
- Change the condition to stop at a different value.
Created nested loops
for (int row = 1; row < 11; row++)
{
Console.WriteLine($"The row is {row}");
}
for (char column = 'a'; column < 'k'; column++)
{
Console.WriteLine($"The column is {column}");
}
for (int row = 1; row < 11; row++)
{
for (char column = 'a'; column < 'k'; column++)
{
Console.WriteLine($"The cell is ({row}, {column})");
}
}
Now that you've seen the if statement and the looping constructs in the C# language, see if you can write C# code to find the sum of all integers 1 through 20 that are divisible by 3. Here are a few hints:
- The % operator gives you the remainder of a division operation.
- The if statement gives you the condition to see if a number should be part of the sum.
- The for loop can help you repeat a series of steps for all the numbers 1 through 20.
Try it yourself. Then check how you did. As a hint, you should get 63 for an answer.
int sum = 0;
for (int number = 1; number < 21; number++)
{
if (number % 3 == 0)
{
sum = sum + number;
}
}
Console.WriteLine($"The sum is {sum}");
data collections using the generic list type
var names = new List<string> { "<name>", "Ana", "Felipe" };
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
Modify list contents
Console.WriteLine();
names.Add("Maria");
names.Add("Bill");
names.Remove("Ana");
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
Console.WriteLine($"My name is {names[0]}.");
Console.WriteLine($"I've added {names[2]} and {names[3]} to the list.");
Console.WriteLine($"The list has {names.Count} people in it");
IndexOf, If the item isn't in the list, IndexOf
returns -1
.
var index = names.IndexOf("Felipe");
if (index != -1)
Console.WriteLine($"The name {names[index]} is at index {index}");
var notFound = names.IndexOf("Not Found");
Console.WriteLine($"When an item is not found, IndexOf returns {notFound}");
Sort
names.Sort();
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
Lists of other types
var fibonacciNumbers = new List<int> {1, 1};
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];
fibonacciNumbers.Add(previous + previous2);
foreach(var item in fibonacciNumbers)
Console.WriteLine(item);
See if you can put together some of the concepts from this and earlier lessons. Expand on what you've built so far with Fibonacci Numbers. Try and write the code to generate the first 20 numbers in the sequence. (As a hint, the 20th Fibonacci number is 6765.)
var fibonacciNumbers = new List<int> {1, 1};
while (fibonacciNumbers.Count < 20)
{
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];
fibonacciNumbers.Add(previous + previous2);
}
foreach(var item in fibonacciNumbers)
Console.WriteLine(item);
2.Explore object oriented programming with classes and objects
Explore object oriented programming with classes and objects
Empty program
using System;
namespace classes
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
In this tutorial, you're going to create new types that represent a bank account. Typically developers define each class in a different text file. That makes it easier to manage as a program grows in size. Create a new file named BankAccount.cs in the classes directory.
This file will contain the definition of a bank account. Object Oriented programming organizes code by creating types in the form of classes. These classes contain the code that represents a specific entity. The BankAccount
class represents a bank account. The code implements specific operations through methods and properties. In this tutorial, the bank account supports this behavior:
- It has a 10-digit number that uniquely identifies the bank account.
- It has a string that stores the name or names of the owners.
- The balance can be retrieved.
- It accepts deposits.
- It accepts withdrawals.
- The initial balance must be positive.
- Withdrawals cannot result in a negative balance.
Define the bank account type
You can start by creating the basics of a class that defines that behavior. Create a new file using the File:New command. Name it BankAccount.cs. Add the following code to your BankAccount.cs file:
using System;
namespace classes
{
public class BankAccount
{
public string Number { get; }
public string Owner { get; set; }
public decimal Balance { get; }
public void MakeDeposit(decimal amount, DateTime date, string note)
{
}
public void MakeWithdrawal(decimal amount, DateTime date, string note)
{
}
}
}
Before going on, let's take a look at what you've built. The namespace declaration provides a way to logically organize your code. This tutorial is relatively small, so you'll put all the code in one namespace.
public class BankAccount defines the class, or type, you are creating. Everything inside the { and } that follows the class declaration defines the state and behavior of the class. There are five members of the BankAccount class. The first three are properties. Properties are data elements and can have code that enforces validation or other rules. The last two are methods. Methods are blocks of code that perform a single function. Reading the names of each of the members should provide enough information for you or another developer to understand what the class does.
Open a new account
public BankAccount(string name, decimal initialBalance)
{
this.Owner = name;
this.Balance = initialBalance;
}
var account = new BankAccount("<name>", 1000);
Console.WriteLine($"Account {account.Number} was created for {account.Owner} with {account.Balance} initial balance.");
private static int accountNumberSeed = 1234567890;
C# Tutorial for Frontend Developer的更多相关文章
- What makes an excellent front-end developer?(for my English speech)
What makes an excellent front-end developer? Let me please start this talking by saying that what is ...
- Front-end Developer Interview Questions
Front-end-Developer-Interview-Questions A list of helpful front-end related questions you can use to ...
- HTML Questions:Front-end Developer Interview Questions
What's a doctype do? Instruct the browser to render the page. What's the difference between standard ...
- jQuery Questions:Front-end Developer Interview Questions
Explain "chaining". Chaining allows us to run multiple jQuery methods (on the same element ...
- JS Questions:Front-end Developer Interview Questions
Explain event delegation Event delegation allows us to attach a single event listener, to a parent e ...
- General Questions:Front-end Developer Interview Questions
What did you learn yesterday/this week? Learning Angular. What excites or interests you about coding ...
- CSS Questions:Front-end Developer Interview Questions
Describe what a "reset" CSS file does and how it's useful. What Is A CSS Reset? A CSS Rese ...
- I want to be a Great Web Front-end Developer
有时觉得特别的浮躁,可能是每天春运般的挤地铁,随处可见因为一点小磕小蹭吹胡子瞪眼睛的人,可能是身边的人貌似一下子都好有钱,买房买车或者买第N套房. 很想静下来心寻找到自己inner pace,但是忽然 ...
- Frontend Development
原文链接: https://github.com/dypsilon/frontend-dev-bookmarks Frontend Development Looking for something ...
随机推荐
- Tableau学习Step4一数据解释、异常值监测、参数使用、分析结果如何对外发布
Tableau学习Step4一数据解释.异常值监测.参数使用.分析结果如何对外发布 本文首发于博客冰山一树Sankey,去博客浏览效果更好. 一. 前言 本教程通过一个案例从浅到深来学习Tableau ...
- 为什么不让用join?《死磕MySQL系列 十六》
大家好,我是咔咔 不期速成,日拱一卒 在平时开发工作中join的使用频率是非常高的,很多SQL优化博文也让把子查询改为join从而提升性能,但部分公司的DBA又不让用,那么使用join到底有什么问题呢 ...
- CF594D题解
我不会数据结构/kk 我想题意应该十分清楚了. 我们知道 \(\varphi(p^k)=p^{k-1}(p-1)\),那么我们考虑将一个询问下放到右端点,然后往右移动右端点并更新每个左端点到右端点的答 ...
- LGP5142题解
题意简明,不说了( 因为教练让同学们做线段树的题,早就会了线段树的我就来爆踩水水蓝了/kk 首先推一下柿子: \[\frac 1 n\sum_{i=1}^n(a_i^2-2 \times a_i \t ...
- ElasticSearch7.3 学习之倒排索引揭秘及初识分词器(Analyzer)
一.倒排索引 1. 构建倒排索引 例如说有下面两个句子doc1,doc2 doc1:I really liked my small dogs, and I think my mom also like ...
- 写给开发人员的实用密码学(七)—— 非对称密钥加密算法 RSA/ECC
本文部分内容翻译自 Practical-Cryptography-for-Developers-Book,笔者补充了密码学历史以及 openssl 命令示例,并重写了 RSA/ECC 算法原理.代码示 ...
- Gin 08 上传文件
单文件上传 cat index.html <!DOCTYPE html> <html lang="en"> <head> <meta ch ...
- 【工程应用五】 opencv中linemod模板匹配算法诸多疑惑和自我解读。
研究这个前前后后也有快两三个月了,因为之前也一直在弄模板匹配方面的东西,所以偶尔还是有不少朋友咨询或者问你有没有研究过linemod这个算法啊,那个效率啥的还不错啊,有段时间一直不以为然,觉得我现在用 ...
- jdbc.properties/(驱动、URL、用户名、密码)跟换数据库时改该配置文件/Untitled Text File格式
背景:这几天从阿里云上面购买了云服务器,最垃圾的那种,还送oss和EDS数据库服务器,只不过EDS数据库服务器只有一个月的,就主动升级为一年的,49还是59忘了.对于配置这种EDS过程中,产生的一个念 ...
- CSI 工作原理与JuiceFS CSI Driver 的架构设计详解
容器存储接口(Container Storage Interface)简称 CSI,CSI 建立了行业标准接口的规范,借助 CSI 容器编排系统(CO)可以将任意存储系统暴露给自己的容器工作负载.Ju ...