0% found this document useful (0 votes)
2 views

C# Overview and Basics

C# is a modern, object-oriented programming language developed by Microsoft, suitable for various applications including web, mobile, and game development. Key features include type safety, automatic memory management, asynchronous programming, and cross-platform support. The document provides an overview of C# syntax, variable declaration, control flow, loops, and object-oriented programming principles.

Uploaded by

alephfirmino
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C# Overview and Basics

C# is a modern, object-oriented programming language developed by Microsoft, suitable for various applications including web, mobile, and game development. Key features include type safety, automatic memory management, asynchronous programming, and cross-platform support. The document provides an overview of C# syntax, variable declaration, control flow, loops, and object-oriented programming principles.

Uploaded by

alephfirmino
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

C# Overview and Basics

Explain C#

C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft as part of the


.NET framework. It is designed to be simple, powerful, and versatile, making it suitable for a wide range
of applications, including desktop software, web applications, cloud services, mobile apps (via Xamarin),
and even game development (with Unity).

Key Features of C#:

1. Object-Oriented Programming (OOP)


Supports classes, inheritance, polymorphism, encapsulation, and interfaces.
2. Type Safety
Strongly typed language that prevents type mismatches at compile-time.
3. Automatic Memory Management
Uses Garbage Collection (GC) to handle memory allocation and deallocation.
4. Asynchronous Programming
Provides async/await for handling asynchronous operations efficiently.
5. LINQ (Language Integrated Query)
Enables querying of collections, databases, XML, and more in a SQL-like syntax.
6. Cross-Platform Development
Originally tied to Windows/.NET Framework, but now supports multiple platforms via .NET
Core and .NET 5+.
7. Interoperability
Can interoperate with C, C++, and even use unmanaged code if needed.
8. Game Development
Widely used in Unity, one of the most popular game engines.

Basic Syntax of C#

Hello World Program

csharp

using System;

class Program {
static void Main() {
Console.WriteLine("Hello, World!");
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/18
`using System;` → Imports the System namespace, which contains essential classes like `Console`.
`class Program {}` → Defines a class named `Program`.
`static void Main()` → Entry point of the program.
`Console.WriteLine("Hello, World!");` → Prints output to the console.

C# Code Basics

Variables and Data Types

csharp

int age = 25; // Integer


double pi = 3.1415; // Floating-point
bool isActive = true; // Boolean
string name = "John"; // String
char letter = 'A'; // Character

Control Flow

csharp

int x = 10;

if (x > 5) {
Console.WriteLine("x is greater than 5");
} else {
Console.WriteLine("x is 5 or less");
}

Loops

csharp

for (int i = 0; i < 5; i++) {


Console.WriteLine($"Iteration {i}");
}

while (x > 0) {
Console.WriteLine(x);
x--;
}

Functions (Methods)

csharp

void SayHello(string name) {


Console.WriteLine($"Hello, {name}!");
}

SayHello("Alice");

Classes and Objects

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/18
csharp

class Person {
public string Name;

public void Greet() {


Console.WriteLine($"Hello, my name is {Name}");
}
}

Person p = new Person();


p.Name = "John";
p.Greet();

Where is C# Used?

Web Development: ASP.NET Core for building web applications and APIs.
Game Development: Unity Engine.
Desktop Applications: Windows Forms, WPF.
Mobile Development: Xamarin.
Cloud Computing: Azure services.
AI & Machine Learning: ML.NET framework.

Would you like me to focus on any specific aspect of C#? 🚀

Explain C# variable syntax

In C#, variables are declared using the syntax:

csharp

<datatype> <variableName> = <value>;

Where:

`<datatype>` specifies the type of data the variable holds (e.g., `int`, `double`, `string`).
`<variableName>` is the name of the variable (follows camelCase by convention).
`<value>` (optional) assigns an initial value to the variable.

Examples of Variable Declarations

csharp

int age = 25; // Integer variable


double price = 9.99; // Floating-point variable
char grade = 'A'; // Character
string name = "Alice"; // String
bool isActive = true; // Boolean (true/false)

Variable Declaration Without Initialization

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/18
Variables can be declared without assigning a value, but they must be assigned before use.

csharp

int number; // Declaration


number = 100; // Assignment
Console.WriteLine(number); // Output: 100

Type Inference (var)

C# allows type inference using `var`, where the compiler automatically determines the type.

csharp

var age = 30; // Inferred as int


var pi = 3.14; // Inferred as double
var message = "Hi"; // Inferred as string

Note: `var` requires an immediate assignment.

Constants (`const` and `readonly`)

Constant Variable (`const`)

A `const` variable is immutable and must be initialized at declaration.

csharp

const double Pi = 3.14159;

Read-Only Variable (`readonly`)

`readonly` allows setting the value only in the constructor.

csharp

class Circle {
public readonly double Radius;

public Circle(double r) {
Radius = r; // Allowed in constructor
}
}

Nullable Variables (`?` Operator)

C# allows nullable value types using `?`.

csharp

int? nullableInt = null; // Can store an int or null


nullableInt = 5; // Now holds an int

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/18
Multiple Variable Declarations

csharp

int x = 10, y = 20, z = 30;

Would you like more details on specific variable types? 😊

Explain C# logic syntax.

C# Logic Syntax (Conditional Statements & Operators)

C# provides various ways to implement logical operations using conditional statements and logical
operators.

1. Conditional Statements
1.1 `if` Statement

Executes a block of code only if the condition is `true`.

csharp

int number = 10;

if (number > 5) {
Console.WriteLine("Number is greater than 5");
}

1.2 `if-else` Statement

Provides an alternative block if the condition is `false`.

csharp

int age = 18;

if (age >= 18) {


Console.WriteLine("You are an adult.");
} else {
Console.WriteLine("You are a minor.");
}

1.3 `else if` Statement

Allows multiple conditions to be checked.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/18
csharp

int score = 85;

if (score >= 90) {


Console.WriteLine("Grade: A");
} else if (score >= 80) {
Console.WriteLine("Grade: B");
} else {
Console.WriteLine("Grade: C or lower");
}

2. Logical Operators
Operator Name Example (`x = 5, y = 10`)
`&&` Logical AND `(x > 3 && y < 15) → true`
` `
`!` Logical NOT `!(x > 3) → false`

Example Using Logical Operators

csharp

bool isSunny = true;


bool isWeekend = false;

if (isSunny && isWeekend) {


Console.WriteLine("Go for a picnic!");
} else {
Console.WriteLine("Stay at home.");
}

3. `switch` Statement (Multiple Conditions)


Used when multiple cases are checked against a variable.

csharp

int day = 3;

switch (day) {
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}

🔹 `break` is required to prevent fall-through.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/18
4. Ternary Operator (`? :`)
A shorthand for `if-else` statements.

csharp

int num = 10;


string result = (num % 2 == 0) ? "Even" : "Odd";
Console.WriteLine(result); // Output: Even

5. Short-Circuit Evaluation
Logical operators `&&` and `||` use short-circuiting, meaning they stop evaluating as soon as the result
is determined.

csharp

int x = 5;
if (x > 0 || SomeFunction()) {
Console.WriteLine("First condition is true, so SomeFunction() is NOT called.");
}

bool SomeFunction() {
Console.WriteLine("This function runs!");
return true;
}

Since `x > 0` is `true`, `SomeFunction()` is never executed.

Would you like examples of more complex logic, such as loops or LINQ filtering? 😊

Explain C# loop syntax.

C# Loop Syntax

Loops in C# allow code to execute repeatedly based on a condition. The main types of loops are:

1. `for` loop – Iterates a fixed number of times.


2. `while` loop – Iterates while a condition is `true`.
3. `do-while` loop – Executes at least once, then continues while a condition is `true`.
4. `foreach` loop – Iterates over collections like arrays or lists.

1. `for` Loop (Fixed Iteration)


Used when the number of iterations is known in advance.
Syntax:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/18
csharp

for (initialization; condition; iteration) {


// Code to execute
}

Example:

csharp

for (int i = 0; i < 5; i++) {


Console.WriteLine($"Iteration {i}");
}

How it works:

1. Initialization → `int i = 0` (runs once).


2. Condition → `i < 5` (loop continues while true).
3. Iteration → `i++` (increment `i` after each iteration).

2. `while` Loop (Conditional Iteration)


Used when the number of iterations is not known in advance.

Syntax:

csharp

while (condition) {
// Code to execute
}

Example:

csharp

int x = 3;
while (x > 0) {
Console.WriteLine($"x = {x}");
x--; // Decrement x
}

3. `do-while` Loop (Runs At Least Once)


Executes at least once, then continues while the condition is `true`.
Syntax:

csharp

do {
// Code to execute
} while (condition);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/18
Example:

csharp

int num = 0;
do {
Console.WriteLine($"num = {num}");
num++;
} while (num < 3);

👉 Even if `num = 0` initially, the loop runs at least once.

4. `foreach` Loop (Iterating Collections)


Used for iterating over collections like arrays, lists, and dictionaries.

Syntax:

csharp

foreach (var item in collection) {


// Code to execute
}

Example:

csharp

string[] fruits = { "Apple", "Banana", "Cherry" };

foreach (string fruit in fruits) {


Console.WriteLine(fruit);
}

5. Loop Control Statements


`break` Statement (Exit Loop)

Stops the loop immediately.

csharp

for (int i = 1; i <= 10; i++) {


if (i == 5) {
break; // Exits loop when i == 5
}
Console.WriteLine(i);
}

`continue` Statement (Skip Iteration)

Skips the rest of the code for the current iteration.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/18
csharp

for (int i = 1; i <= 5; i++) {


if (i == 3) {
continue; // Skip when i == 3
}
Console.WriteLine(i);
}

👉 Output: `1, 2, 4, 5` (3 is skipped).

6. Nested Loops
Loops inside loops.

csharp

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 3; j++) {
Console.WriteLine($"i={i}, j={j}");
}
}

Would you like an example of a more complex loop logic? 😊

Explain C# OOP syntax.

C# Object-Oriented Programming (OOP) Syntax

C# follows the OOP (Object-Oriented Programming) paradigm, which includes the core principles:
✅ Encapsulation (Data Hiding)
✅ Inheritance (Code Reusability)
✅ Polymorphism (Method Overriding & Overloading)
✅ Abstraction (Hiding Implementation Details)
1. Classes & Objects
A class is a blueprint for creating objects.
An object is an instance of a class.

Syntax:

csharp

class Person {
// Fields (Private)
private string name;

// Constructor
public Person(string name) {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/18
this.name = name;
}

// Method
public void Greet() {
Console.WriteLine($"Hello, my name is {name}.");
}
}

// Creating and using an object


Person p = new Person("Alice");
p.Greet(); // Output: Hello, my name is Alice.

🔹 fields cannot be accessed directly from outside.


🔹
`private`
`public` methods control access to private fields.

2. Encapsulation (`private` & `public`)


Encapsulation hides data using access modifiers:

Modifier Access Scope

`public` Accessible everywhere


`private` Accessible only inside the same class

`protected` Accessible inside the same class & subclasses

`internal` Accessible within the same assembly

Example with Getters & Setters

csharp

class Car {
private string model;

// Property (Encapsulated Access)


public string Model {
get { return model; }
set { model = value; }
}
}

// Usage
Car myCar = new Car();
myCar.Model = "Tesla"; // Using setter
Console.WriteLine(myCar.Model); // Output: Tesla

🔹 Properties ( `get` and `set`) allow controlled access to fields.

3. Inheritance (`: ParentClass`)


Inheritance allows a child class to derive from a parent class.

csharp

class Animal {
public void Speak() {
Console.WriteLine("Animal makes a sound");
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/18
// Dog class inherits from Animal
class Dog : Animal {
public void Bark() {
Console.WriteLine("Dog barks");
}
}

// Usage
Dog myDog = new Dog();
myDog.Speak(); // Inherited method
myDog.Bark(); // Child method

🔹 The `Dog` class inherits the `Speak()` method from `Animal`.

4. Polymorphism (Method Overriding & Overloading)


Polymorphism allows methods to have different forms.

4.1 Method Overriding (`virtual` & `override`)

Allows a subclass to modify a method from the parent class.

csharp

class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}

class Cat : Animal {


public override void Speak() {
Console.WriteLine("Cat meows");
}
}

// Usage
Animal myAnimal = new Cat();
myAnimal.Speak(); // Output: Cat meows (Overridden method)

🔹 allows overriding.
🔹
`virtual`
`override` modifies the behavior in the subclass.

4.2 Method Overloading (Same Method, Different Parameters)

csharp

class MathOperations {
public int Add(int a, int b) {
return a + b;
}

public double Add(double a, double b) {


return a + b;
}
}

// Usage
MathOperations math = new MathOperations();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/18
Console.WriteLine(math.Add(2, 3)); // Output: 5
Console.WriteLine(math.Add(2.5, 3.5)); // Output: 6.0

🔹 Same method name, different parameters.


5. Abstraction (`abstract` & `interface`)
Abstraction hides implementation details and enforces structure.

5.1 Abstract Class (Partial Implementation)

csharp

abstract class Shape {


public abstract void Draw(); // No implementation
}

class Circle : Shape {


public override void Draw() {
Console.WriteLine("Drawing a circle");
}
}

// Usage
Shape s = new Circle();
s.Draw(); // Output: Drawing a circle

🔹 Abstract methods must be implemented in derived classes.


🔹 Cannot create an instance of an abstract class.
5.2 Interface (Pure Abstraction)

csharp

interface IAnimal {
void Speak(); // No implementation
}

class Dog : IAnimal {


public void Speak() {
Console.WriteLine("Dog barks");
}
}

// Usage
IAnimal animal = new Dog();
animal.Speak(); // Output: Dog barks

🔹 Interfaces only contain method signatures.


🔹 Classes must implement all interface methods.
6. Static Members (Shared Across All Instances)
A static method or field belongs to the class itself, not instances.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/18
csharp

class MathHelper {
public static double Pi = 3.14159;

public static int Square(int num) {


return num * num;
}
}

// Usage
Console.WriteLine(MathHelper.Pi); // Output: 3.14159
Console.WriteLine(MathHelper.Square(4)); // Output: 16

🔹 No need to create an instance ( `MathHelper.Square(4)`).

Summary of OOP Features in C#


Feature Description

Encapsulation Hiding data with private fields & public properties


Inheritance Allows a class to derive from another class (`class Child : Parent`)
Polymorphism Enables method overriding (`override`) and overloading

Abstraction Hides details using `abstract` classes or `interface`

Would you like an example of more advanced OOP concepts like dependency
injection or SOLID principles? 😊

convert to c#:

import requests
import math
import time
from IPython.display import clear_output

def leverage (entry_usdt, stop_usdt, capital, maximum_risk, coin_usdt, entry_fee = 0.0005, exit_fee =
0.0005):
return <SECRET FORMULA>

def profit (entry_usdt, close_usdt, capital, coin_usdt, leverage, direction, entry_fee = 0.0005, exit_fee
= 0.0005):
mult = 1
if direction == 1:
if close_usdt < entry_usdt :
mult = -1
elif direction == -1:
if close_usdt > entry_usdt:
mult = -1

return [SECRET FORMULA]


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/18
def get_mark_price(symbol="DOGEUSDT"):
url = "https://testnet.binancefuture.com/fapi/v1/premiumIndex"
params = {"symbol": symbol}

response = requests.get(url, params=params)


if response.status_code == 200:
return response.json()
else:
return {"error": f"Request failed with status code {response.status_code}", "details":
response.text}

Here's the equivalent C# implementation of your Python code:


Convert Crypto Calc

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/18
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class CryptoTrading
{
public static double Leverage(double entryUsdt, double stopUsdt, double capital, double maximumR
{
return SECRET_FORMULA;
}

public static double Profit(double entryUsdt, double closeUsdt, double capital, double coinUsdt,
{
int mult = 1;
if (direction == 1 && closeUsdt < entryUsdt)
{
mult = -1;
}
else if (direction == -1 && closeUsdt > entryUsdt)
{
mult = -1;
}

return SECRET_FORMULA;
}

public static async Task<JObject> GetMarkPrice(string symbol = "DOGEUSDT")


{
using (HttpClient client = new HttpClient())
{
string url = "https://testnet.binancefuture.com/fapi/v1/premiumIndex";
string fullUrl = url + "?symbol=" + symbol;
HttpResponseMessage response = await client.GetAsync(fullUrl);

if (response.IsSuccessStatusCode)
{
string jsonResponse = await response.Content.ReadAsStringAsync();
return JObject.Parse(jsonResponse);
}
else
{
return new JObject
{
{ "error", $"Request failed with status code {response.StatusCode}" },
{ "details", await response.Content.ReadAsStringAsync() }
};
}
}
}
}

This C# code replicates the functionality of your Python script, including:

1. Leverage Calculation (`Leverage` method) – Placeholder for your secret formula.


2. Profit Calculation (`Profit` method) – Uses `mult` logic from your Python function.
3. Fetching Market Price (`GetMarkPrice` method) – Makes an HTTP request to Binance and returns
a JSON object.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/18
Let me know if you need modifications or additional features! 🚀

mathematical formula in c#

In C#, you can use the `System.Math` library for mathematical operations. Here’s how you can write
formulas using C# syntax:

Basic Mathematical Operations

csharp

double result = (10 + 5) * 2 / 4.0; // Output: 7.5

Power and Square Root

csharp

double power = Math.Pow(2, 3); // 2^3 = 8


double sqrt = Math.Sqrt(16); // sqrt(16) = 4

Trigonometric Functions

csharp

double sinValue = Math.Sin(Math.PI / 2); // sin(90°) = 1


double cosValue = Math.Cos(0); // cos(0) = 1
double tanValue = Math.Tan(Math.PI / 4); // tan(45°) = 1

Logarithm and Exponential

csharp

double logValue = Math.Log(10); // Natural log (ln)


double log10Value = Math.Log10(100); // Log base 10
double expValue = Math.Exp(2); // e^2

Rounding and Absolute Value

csharp

double roundValue = Math.Round(3.14159, 2); // 3.14


double absValue = Math.Abs(-5); // 5

Example: Your Secret Formula in C#

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/18
csharp

double Leverage(double entryUsdt, double stopUsdt, double capital, double maximumRisk, double coinUs
{
return (capital * maximumRisk) / ((entryUsdt - stopUsdt) * coinUsdt * (1 + entryFee + exitFee))
}

Let me know if you need a specific formula! 😊

I need to import to use Math in c#?

No, you do not need to import anything to use `Math` in C# because it is part of the System namespace,
which is included by default.

Example Usage

csharp

using System; // No need to explicitly import Math, as it's in System

class Program
{
static void Main()
{
double sqrtValue = Math.Sqrt(25); // Square root
double powerValue = Math.Pow(2, 3); // 2^3
double piValue = Math.PI; // Constant Pi

Console.WriteLine($"Square Root: {sqrtValue}"); // Output: 5


Console.WriteLine($"Power: {powerValue}"); // Output: 8
Console.WriteLine($"Pi: {piValue}"); // Output: 3.141592653589793
}
}

✅ No need to import anything extra!


✅ functions are built into System.Math and work out of the box. 🚀
`Math`

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/18

You might also like