SlideShare a Scribd company logo
Covariance, Contravariance 觀念分享
                             Howard
Covariance

string[] strings = new string[3];
object[] objects = strings;

// RunTimeError !! 發生 ArrayTypeMismatchException!
objects[0] = DateTime.Now;
string s = (string)objects[0];
Covariance – generic types


List<string> stringList = new List<string>();
List<object> objectList = stringList;

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to
'System.Collections.Generic.List<object>’


泛型本身具有不變性( invariance )
Covariance in .Net 4.0
List<string> stringList = new List<string>();

// C# 2/3 不允許, C# 4.0 OK!
IEnumerable<object> objects = stringList;



WHY ?
Covariance in .Net 4.0
public interface IEnumerable<out T> : Ienumerable
{

     IEnumerator<T> GetEnumerator();
}

型別 T 在這個泛型介面中只能用於 method 的傳回值,而不能用來當
作 method 的參數

public interface IFoo<out T>
{
          // 編譯失敗:型別 T 在這裡只能用於方法的傳回值,不可當
作參數。
          string Convert(T obj);
          T GetInstance();    // OK!
}
Covariance in .Net 4.0
 用 IEnumerable<T> 把一串物件包起來,難道不會跟前面
 的陣列 covariance 範例一樣產生型別安全的問題嗎?

 答案是不會。因為 IEnumerable<T> 的操作都是唯讀的,你無法透
 過它去替換或增刪串列中的元素。
Contravariance
   跟 Covariance 相反 - in

static object GetObject() { return null; }
     static void SetObject(object obj) { }
     static string GetString() { return ""; }
     static void SetString(string str) { }


static void Test()
     {
       // Covariance. A delegate specifies a return type as object,
       // but you can assign a method that returns a string.
       Func<object> del = GetString;

  // Contravariance. A delegate specifies a parameter type as string,
       // but you can assign a method that takes an object.

  Action<string> del2 = SetObject;
    }
Contravariance

public interface MyIComparer<in Tin>
{

       int Compare(Tin left, Tin right);
}
結論
 In .NET Framework 4, both C# and Visual Basic support
  covariance and contravariance in generic interfaces and
  delegates and allow for implicit conversion of generic type
  parameters.
Reference
 C# 4.0 : Covariance 與 Contravariance 觀念入門
   http://huan-lin.blogspot.com/2009/10/c-40covariance-and-
     contravariance.html

 Covariance and Contravariance (C# and Visual Basic)
   http://msdn.microsoft.com/en-us/library/ee207183.aspx
Q&A

More Related Content

What's hot

JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
Chris Farrell
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
rnkhan
 
Type conversions
Type conversionsType conversions
Type conversions
sanya6900
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
Gamindu Udayanga
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
Danial Mirza
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift generics
Denis Poifol
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
Docent Education
 
#4 (Remote Method Invocation)
#4 (Remote Method Invocation)#4 (Remote Method Invocation)
#4 (Remote Method Invocation)
Ghadeer AlHasan
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
sangrampatil81
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NET
Dmitri Nesteruk
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
aravind_aashu
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
Sachin Sharma
 
Pointers
PointersPointers
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
Philip Schwarz
 
Pointers
PointersPointers
Pointers
Lp Singh
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
Tushar Shende
 
Function in C++
Function in C++Function in C++
Function in C++
Prof Ansari
 

What's hot (20)

JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
Type conversions
Type conversionsType conversions
Type conversions
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
Data Type Conversion in C++
Data Type Conversion in C++Data Type Conversion in C++
Data Type Conversion in C++
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift generics
 
16 virtual function
16 virtual function16 virtual function
16 virtual function
 
#4 (Remote Method Invocation)
#4 (Remote Method Invocation)#4 (Remote Method Invocation)
#4 (Remote Method Invocation)
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
 
CallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NETCallSharp: Automatic Input/Output Matching in .NET
CallSharp: Automatic Input/Output Matching in .NET
 
Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0Java%20 new%20faq.doc 0
Java%20 new%20faq.doc 0
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 
Pointers
PointersPointers
Pointers
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Java String
Java String Java String
Java String
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
Pointers
PointersPointers
Pointers
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Function in C++
Function in C++Function in C++
Function in C++
 

Viewers also liked

Strawberries
StrawberriesStrawberries
Strawberries
ebanreb07
 
2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements
Top10Supplements.com
 
Choice Art Group Web Transformation Project
Choice Art Group Web Transformation ProjectChoice Art Group Web Transformation Project
Choice Art Group Web Transformation Project
Benjamin Berman
 
Kees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragenKees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragennvbonline
 
Pedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HEPedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HE
Tansy Jessop
 
Projectphp
ProjectphpProjectphp
Projectphp
kneelabh
 
V Игры "Дети Азии" коммуникационный проект
V Игры "Дети Азии"   коммуникационный проектV Игры "Дети Азии"   коммуникационный проект
V Игры "Дети Азии" коммуникационный проектVlad Shulaev
 
50 states assignment
50 states assignment50 states assignment
50 states assignment
maddycortez
 
Sardegna. Artigianato sardo.
Sardegna. Artigianato sardo.Sardegna. Artigianato sardo.
Sardegna. Artigianato sardo.
Agriturismo b&b Le Camelie
 
214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...ivanov15666688
 
A multi agent based decision mechanism for incident reaction in telecommunica...
A multi agent based decision mechanism for incident reaction in telecommunica...A multi agent based decision mechanism for incident reaction in telecommunica...
A multi agent based decision mechanism for incident reaction in telecommunica...
Luxembourg Institute of Science and Technology
 
Social studies
Social studiesSocial studies
Social studies
Darron Arlt
 
Davies2006
Davies2006Davies2006
Lorian Boulevard
Lorian BoulevardLorian Boulevard
Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967
idn12
 
Democratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions EverywhereDemocratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions Everywhere
Brandwatch
 
Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2
Sri Suwanti
 
Linked Data and Public Administration
Linked Data and Public AdministrationLinked Data and Public Administration
Linked Data and Public Administration
Oscar Corcho
 

Viewers also liked (18)

Strawberries
StrawberriesStrawberries
Strawberries
 
2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements2014's Top 10 Best Carnitine Supplements
2014's Top 10 Best Carnitine Supplements
 
Choice Art Group Web Transformation Project
Choice Art Group Web Transformation ProjectChoice Art Group Web Transformation Project
Choice Art Group Web Transformation Project
 
Kees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragenKees Riekwel - Info battle finalevragen
Kees Riekwel - Info battle finalevragen
 
Pedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HEPedagogic implications of wider purpose of HE
Pedagogic implications of wider purpose of HE
 
Projectphp
ProjectphpProjectphp
Projectphp
 
V Игры "Дети Азии" коммуникационный проект
V Игры "Дети Азии"   коммуникационный проектV Игры "Дети Азии"   коммуникационный проект
V Игры "Дети Азии" коммуникационный проект
 
50 states assignment
50 states assignment50 states assignment
50 states assignment
 
Sardegna. Artigianato sardo.
Sardegna. Artigianato sardo.Sardegna. Artigianato sardo.
Sardegna. Artigianato sardo.
 
214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...214.экономика метод указания по выполнению контрольной работы для студентов з...
214.экономика метод указания по выполнению контрольной работы для студентов з...
 
A multi agent based decision mechanism for incident reaction in telecommunica...
A multi agent based decision mechanism for incident reaction in telecommunica...A multi agent based decision mechanism for incident reaction in telecommunica...
A multi agent based decision mechanism for incident reaction in telecommunica...
 
Social studies
Social studiesSocial studies
Social studies
 
Davies2006
Davies2006Davies2006
Davies2006
 
Lorian Boulevard
Lorian BoulevardLorian Boulevard
Lorian Boulevard
 
Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967Vintage Power Boat Racing Program Havasu 1967
Vintage Power Boat Racing Program Havasu 1967
 
Democratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions EverywhereDemocratizing Data & Decision-Making: Better Decisions Everywhere
Democratizing Data & Decision-Making: Better Decisions Everywhere
 
Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2Learning Bahasa Indonesia the Easy Way 2
Learning Bahasa Indonesia the Easy Way 2
 
Linked Data and Public Administration
Linked Data and Public AdministrationLinked Data and Public Administration
Linked Data and Public Administration
 

Similar to Covariance, contravariance 觀念分享

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
Paulo Morgado
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
SachinBhosale73
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
Anand Kumar Rajana
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
Advance Java
Advance JavaAdvance Java
Advance Java
Vidyacenter
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
Kevin Pilch
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
CodeOps Technologies LLP
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
Shakir Majeed Khan
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
imypraz
 
PostThis
PostThisPostThis
PostThis
testingphase
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
Md. Mahedee Hasan
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
maxinesmith73660
 
Linq intro
Linq introLinq intro
Linq intro
Bình Trọng Án
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
DhrumilSheth3
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
VivekSharma34623
 

Similar to Covariance, contravariance 觀念分享 (20)

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
PostThis
PostThisPostThis
PostThis
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxConsider this code using the ArrayBag of Section 5.2 and the Locat.docx
Consider this code using the ArrayBag of Section 5.2 and the Locat.docx
 
Linq intro
Linq introLinq intro
Linq intro
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptxvectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
vectors.(join ALL INDIA POLYTECHNIC (AICTE)).pptx
 

More from LearningTech

vim
vimvim
PostCss
PostCssPostCss
PostCss
LearningTech
 
ReactJs
ReactJsReactJs
ReactJs
LearningTech
 
Docker
DockerDocker
Docker
LearningTech
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
LearningTech
 
node.js errors
node.js errorsnode.js errors
node.js errors
LearningTech
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
LearningTech
 
Expression tree
Expression treeExpression tree
Expression tree
LearningTech
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
LearningTech
 
flexbox report
flexbox reportflexbox report
flexbox report
LearningTech
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
LearningTech
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
LearningTech
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
LearningTech
 
Node child process
Node child processNode child process
Node child process
LearningTech
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
LearningTech
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
LearningTech
 
Expression tree
Expression treeExpression tree
Expression tree
LearningTech
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
LearningTech
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
LearningTech
 
git command
git commandgit command
git command
LearningTech
 

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Recently uploaded

Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 

Recently uploaded (20)

Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 

Covariance, contravariance 觀念分享

  • 2. Covariance string[] strings = new string[3]; object[] objects = strings; // RunTimeError !! 發生 ArrayTypeMismatchException! objects[0] = DateTime.Now; string s = (string)objects[0];
  • 3. Covariance – generic types List<string> stringList = new List<string>(); List<object> objectList = stringList; Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<object>’ 泛型本身具有不變性( invariance )
  • 4. Covariance in .Net 4.0 List<string> stringList = new List<string>(); // C# 2/3 不允許, C# 4.0 OK! IEnumerable<object> objects = stringList; WHY ?
  • 5. Covariance in .Net 4.0 public interface IEnumerable<out T> : Ienumerable { IEnumerator<T> GetEnumerator(); } 型別 T 在這個泛型介面中只能用於 method 的傳回值,而不能用來當 作 method 的參數 public interface IFoo<out T> { // 編譯失敗:型別 T 在這裡只能用於方法的傳回值,不可當 作參數。 string Convert(T obj); T GetInstance(); // OK! }
  • 6. Covariance in .Net 4.0  用 IEnumerable<T> 把一串物件包起來,難道不會跟前面 的陣列 covariance 範例一樣產生型別安全的問題嗎? 答案是不會。因為 IEnumerable<T> 的操作都是唯讀的,你無法透 過它去替換或增刪串列中的元素。
  • 7. Contravariance  跟 Covariance 相反 - in static object GetObject() { return null; } static void SetObject(object obj) { } static string GetString() { return ""; } static void SetString(string str) { } static void Test() { // Covariance. A delegate specifies a return type as object, // but you can assign a method that returns a string. Func<object> del = GetString; // Contravariance. A delegate specifies a parameter type as string, // but you can assign a method that takes an object. Action<string> del2 = SetObject; }
  • 8. Contravariance public interface MyIComparer<in Tin> { int Compare(Tin left, Tin right); }
  • 9. 結論  In .NET Framework 4, both C# and Visual Basic support covariance and contravariance in generic interfaces and delegates and allow for implicit conversion of generic type parameters.
  • 10. Reference  C# 4.0 : Covariance 與 Contravariance 觀念入門  http://huan-lin.blogspot.com/2009/10/c-40covariance-and- contravariance.html  Covariance and Contravariance (C# and Visual Basic)  http://msdn.microsoft.com/en-us/library/ee207183.aspx
  • 11. Q&A