📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Classes
  • Creating objects
  • The static modifier
  • Structs
  • Arrays
  • Incomplete arrays
  • Strings
  • Enums
  • Reference vs. Value Types
  • Copying vs. referencing
  1. Csharp
  2. C Sharp Fundamentals

Non Primitive Types

Non-primitive types include

  • Classes

  • Strings

  • Structs

  • Arrays

  • Enums

  • And more

Classes

Classes have fields and methods. They are used to create objects, which become instances of those classes.

To create a class, we write:

public class Person
{
  // Field
  public string Name;

  // Method
  public void Introduce()
  {
    Console.WriteLine("Hi, name is " + Name);
  }
}

Note: ``public` is an access modifier. It determines who can access the class or field or method.

Creating objects

Creating an object is sort of like declaring any variable: you provide a type and a variable name.

int number;
Person person = new Person();

The only difference is that you have to explicitly call new ClassName(). (You do this to tell C# to allocate memory for your object.)

Note: You can use var Person = new Person(); here too, and C# will make a best guess what data type the variable is.

The static modifier

A static modifier uses the static keyword to make a field or method accessible via the class itself (instead of the object instance).

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

int result = Calculator.Add(1, 2);

Note: When you use static, the field or method is not accessible in the object instance. At the same time, this means the field or method is not duplicated in memory for every object instance either; it's only found once in the class itself.

Structs

Structs are like classes except more lightweight (there a lot of subtle differences).

Pro tip: 99% of the time, you'll be creating classes, not structs. Use structs when you want something small and lightweight. This is especially useful if you're creating 1000s of objects of that type, as small and lightweight means less load for the computer.

Good candidates for structs:

public struct RgbColor
{
  public int Red;
  public int Green;
  public int Blue;
}

public struct Coordinate
{
  public float Latitude;
  public float Longitude;
}

Note: All primitive data types like int or bool are actually structs! To see this for yourself, just type int number; and hover over int. As a result, these 2 variable declarations are the same!

int number;
Int32 number;

Arrays

Arrays store a fixed-size collection of variables of the same type.

// This is an array that accepts 3 integers
int[] numbers = new int[3] { 1, 2, 3 };

// Alternatively, you can add the items after initialization
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;

Note: Once again, we use the new keyword to explicitly allocate memory for the array, as C# won't do that automatically for us.

Pro tip: When you create a new array, internally you are actually creating an instance of a class. That's why it looks like a class so much.

Incomplete arrays

Notice what happens when you use an array where not all items have been set in the array:

int[] numbers = new int[3];
numbers[0] = 1;

Console.WriteLine(numbers[0]); // prints 1
Console.WriteLine(numbers[1]); // prints 0
Console.WriteLine(numbers[2]); // prints 0

When items are not set in an array, the value falls back to the default for that data type. In this case, the default for int is 0.

Strings

Strings are just sequences of characters denoted by the double quotes: "hello world".

// String literal
string name = "Dan Fitz";
// String concatenation
string anotherName = firstName + " " + lastName;
// String format
string altName = string.Format("{0} {1}", firstName, lastName);
// String join (using an array)
var numbers = new int[3] { 1, 2, 3 };
string list = string.Join(",", numbers);
// Accessing string characters
string simpleName = "Mosh";
char firstChar = simpleName[0];

Strings are immutable. Once you create them, you can't change them.

string name = "Dan";
name[0] = "M"; // doesn't work

Verbatim strings prefix @, so you don't have to use escape characters in your string.

// String with escape characters
string path = "c:\\projects\\project1\\folder1";
// Verbatim string
string path = @"c:\projects\project1\folder";

Note: Behind the scenes, strings are actually classes. As a result, these 2 variable declarations are the same!

string firstName = "Dan";
String lastName = "Fitz";

Enums

Enums are data types that represent a set of name-value pairs or constants.

Pro tip: Enums are especially useful when you have a set of constants in your application, so it's cleaner to group them together.

// Instead of this...
const int RegularShipping = 1;
const int ExpressShipping = 2;

// Do this
public enum ShippingMethod
{
  Regular = 1,
  Express = 2;
}

Note: Think of the integers as ids for each constant in the enum.

Enums are useful for getting at values when you have one already available.

// Get an int from an enum using casting
var method = (int)ShippingMethod.Express; // returns 2

// Get an enum from an int using casting
var methodId = (ShippingMethod)2; // returns "Express" enum

// Parse a string into an enum
var shippingMethod = Enum.Parse(typeof(ShippingMethod), "Express"); // returns "Express" enum

Note: Enum.Parse is a way of converting a data type into a specified enum.

Reference vs. Value Types

As mentioned previously, it turns out that all primitive data types are structs because they're smaller; they take no more than 8 bytes of memory. And all non-primitive data types like arrays and strings are classes; they're treated differently during memory management.

Structs are value types because

  • Memory is allocated on the stack

  • Memory is allocated automatically

  • When value is out of scope, it is removed from the stack

Classes are reference types because

  • Memory is allocated on the heap (more sustainable data structure)

  • Memory must be manually allocated using new

  • When object is out of scope, it will remain in the heap for a little while; later, it will be garbage collected by the CLR

Copying vs. referencing

When you assign a variable containing a value type into a new variable, that value is copied in memory. As a result, those 2 variables are independent: changing one doesn't change the other.

var a = 10;
var b = a;
b++;

Console.WriteLine(a); // prints 10
Console.WriteLine(b); // prints 11

Behind the scenes, a is in the stack. Then we copy the contents of a into a new memory location in the stack that we call b.

In contrast, when you assign a variable containing a reference type into a new variable, that value is referenced in memory. In other words, both variables are pointing to the same location in memory: changing one changes the other (because they're the same thing).

var array1 = new int[3] { 1, 2, 3 };
var array2 = array1;
array2[0] = 0;

Console.WriteLine(array1[0]); // prints 0
Console.WriteLine(array2[0]); //prints 0

Behind the scenes, the variable array1 is stored in the stack containing a memory address that references a memory location in the heap containing the contents of the actual array. As a result, when you store the contents of array1 to array2, you're just copying the memory address.

PreviousPrimitive Types And ExpressionsNextControl Flow

Last updated 3 years ago