Advertisement
kanagara

C# razlika izmedju strukture i klase.

Nov 15th, 2020
1,256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.01 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.                    
  4. public class Program
  5. {
  6.     public static void Main()
  7.     {
  8.         X x = new X(){x = 0};
  9.         //Posto je y property klase Y, nije potrebno praviti konstruktor koji ce primati int kao parametar, jer je y property.
  10.         Y y = new Y() {y = 0};
  11.        
  12.         IncrementClass(x);
  13.         Console.WriteLine(x.x); // Bice ispisana 1, zato sto se klasa proseldjuje po referenci.
  14.         IncrementStruct(y);
  15.    
  16.         Console.WriteLine(y.y); //Bice ispisana 0, zato sto se struktura prosledjuje po vrednosti tj pravi se kopija prosledjenog parametra.
  17.         IncrementStruct(ref y); //Ukoliko se koristi ref kljucna rec, prosledice se stvarni parametar koji se nece kopirati
  18.         Console.WriteLine(y.y); //Bice ispisana 1
  19.     }
  20.    
  21.    
  22.     public static void IncrementClass(X x){
  23.         x.x++;
  24.     }
  25.    
  26.     public static void IncrementStruct(Y y){
  27.         y.y++; 
  28.     }
  29.    
  30.    
  31.     public static void IncrementStruct(ref Y y){
  32.         y.y++; 
  33.     }
  34.    
  35.     public class X{
  36.         public int x{get;set;}
  37.     }
  38.    
  39.     public struct Y{
  40.         public int y {get;set;}
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement